在提交我的React表单后,有没有一种更简单的方法可以将对象传递到我想要重定向的页面



我使用的是React 16.13.0。我有下面的处理程序来将我的React表单提交到它的端点。。。

const handleFormSubmit = (e) => {
...
fetch(REACT_APP_PROXY + "/coops/", {
method: "POST",
body: JSON.stringify(NC),
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw response; 
}
})
.then((data) => {
const result = data;
window.location.href = "/" + result.id + "/people";
}).catch(err => {
err.text().then( errorMessage => { 
setErrors({ errors: errorMessage });
}); 
});
};

我想知道是否还有更多的";React";重定向到下一页的方式。现在,我正在做

window.location.href = "/" + result.id + "/people";

这看起来有点古怪。此外,我无法将对象传递到下一页,因为我在执行提交的页面上有一个对象(理想情况下,"数据"对象是我想传递给下一页的对象(。因此,当重定向页面加载时,我被迫执行另一个fetch调用来再次检索该对象。

React,在页面加载/位置更改之间传递对象:

  • 您可以使用此处接受答案中所述的localStorage/sessionStorage
  • 或者使用React Context或Redux以全局状态存储对象,该对象在应用程序中共享

React,Routing&传递对象:

首先,更新window.location没有什么问题。这是更新当前页面的有效方式。保持原样并使用sessionStorage传递对象很可能是解决问题的最快方法。话虽如此,还有一些更优化的解决方案更像是react:例如,试试react Router。它还允许您通过将对象作为道具传递到其他页面来在路线之间传递对象。

react路由器dom挂钩示例:

import { useHistory } from "react-router-dom";
const myComponent = () => {
const history = useHistory();
...
.then((data) => {
const result = data;
// access state via this.props.location.state.result
history.push({
pathname: "/" + result.id + "/people",
state: {result}
});
}).catch(err => {
err.text().then( errorMessage => { 
setErrors({ errors: errorMessage });
}); 
});
}

在此处查找有关react路由器dom的更多信息。

最新更新