我无法使用react-router dom中的useHistory history.push方法通过状态发送参数。
现在假设我想将更多的字符串传递给Paging组件,即一些道具。
未定义为状态值状态引发错误的我的分页组件
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} />
答案 0 :(得分:1)
您需要将Route参数传递给渲染的组件,以便它可以使用它们
const ProtectedSystem = ({auth , component: Component, ...rest}) =>{
return(
<Route
{...rest}
render={(routeParams) => auth ? (<Component {...routeParams}/>) : (<Redirect to = '/' /> )}
/>
)
}
答案 1 :(得分:0)
您可以完全使用React钩子和纯函数来完成此操作,例如
C:\Ruby26-x64\lib\ruby\gems\2.6.0\gems\devise-4.7.3\app\controllers\devise\registrations_controller.rb