【问题标题】:How to pass state in history.push in React-Router如何在 React-Router 中传递 history.push 中的状态
【发布时间】: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


【解决方案1】:

您需要将 Route 参数传递给渲染的组件,以便它可以使用它们

const ProtectedSystem = ({auth , component: Component, ...rest}) =>{
    return(
        <Route 
        {...rest}
        render={(routeParams) => auth ?  (<Component {...routeParams}/>) : (<Redirect to = '/' /> )}
        />
    )
} 

【讨论】:

【解决方案2】:

你可以完全使用 React 钩子和纯函数来做到这一点,例如。

import React from 'react';
import { useHistory } from 'react-router-dom';

const ProtectedSystem = ({ auth }) => {
  const history = useHistory();
  if (!authUser) {
    history.push("/signin");
  }
  return (
    <div><h1>Authorized user</h1></div>
  )
}
export default ProtectedSystem

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 2019-10-19
    • 2017-05-18
    • 1970-01-01
    • 2018-02-20
    相关资源
    最近更新 更多