【发布时间】:2020-08-29 06:12:55
【问题描述】:
我无法使用 react-router dom 中的 useHistory history.push 方法通过状态发送参数。
现在假设我想向分页组件传递多个字符串,即一些道具。
未定义状态值状态引发错误的我的分页组件
const PAGING = ({ location }) => {
console.log(location);
console.log(location.state);
console.log(location.state.id);
return <div>Hello <div>}
另一个组件中的History.push方法
const handleDetails = (id,name) => {
console.log(name)
if (id) {
return history.push({
pathname: `/detailing/${name}`,
state: { id }
});
} else {
return history.push("/");
}
};
const Switch = () => {
const { state: authState } = useContext(AuthContext)
return (
<div>
<Router>
<Switch>
<ProtectedSystem
path= "/detailing/:name"
exact
auth={authState.isAuthenticated}
component={PAGING}
/>
</Switch>
</Router>
</div>
);
const ProtectedSystem = ({auth , component: Component, ...rest}) =>{
return(
<Route
{...rest}
render={() => auth ? (<Component/>) : (<Redirect to = '/' /> )}
/>
)
}
如果我使用没有条件的简单路线,它的工作正常
<Route path= "/detailing/:name" exact component={PAGING} />
【问题讨论】:
-
什么没有按预期工作?或者更确切地说,你想做什么?带有状态的 history.push 似乎是正确的。
-
当我的 PAGING 组件加载时,
console.log(location.state);会抛出错误 -
啊,我明白了。 @ShubhamKhatri 有它,尽管我建议稍微重构一下代码,以便
ProtectedSystem总是返回一个路由或重定向,即将身份验证上下文 移入 它并确定要返回哪个,路由道具会不过仍然需要通过管道传递给他们。
标签: reactjs react-router