【问题标题】:how to maintain history state by using react-router-dom among components?如何通过在组件之间使用 react-router-dom 来维护历史状态?
【发布时间】:2020-07-16 23:23:55
【问题描述】:

我有一个用例,我使用 useHistory 挂钩在组件之间重定向和传递状态。

/* first component */

const {useHistory} from 'react-router-dom';
const history = useHistory();
history.push({pathname: '/next',course: 'some value'});

/* second component */

const location = useLocation();
const value = location.course; /* return 'some value' */
history.push('/nextroute') /* redirects to the third component */

现在,当我从浏览器按返回按钮时,会出现问题,位置状态未定义。现在我有视图,我必须使用“历史”来重定向并将状态传递给组件。当我按下浏览器上的后退按钮或发生页面刷新时,如何保持该状态。还有什么其他效果方式可以为这个特定的用例传递状态。

【问题讨论】:

    标签: javascript reactjs react-router-dom browser-history


    【解决方案1】:

    如果我理解正确,我认为您收到的是 undefined,因为 react 路由器覆盖了您的课程价值。

    将您的课程值推送到 location.state 而不是位置本身,例如:

    history.push({
      pathname: '/next',
      state: {
        course: 'some value'
      }
    });
    

    然后你可以在你的下一个组件中使用history.location.state.course;访问它

    您可能会变得不确定,因为您正在尝试返回第一个表单并且尚未为该路线设置状态。您首先需要替换状态,然后像这样推送到新表单:

    // replace the current routes state
    history.replace({
      pathname: "/",
      state: {
        courses: 'your stuff'
      }
    });
    
    //then push this state to your next route for use there
    history.push({
      pathname: "/next",
      state: {
        courses: 'your stuff'
      }
    });
    

    这是一个简单的例子Codesandbox Example

    注意:如果您想要一个特定于每条路线的状态对象,请使用位置状态来存储您的数据。如果您的一般状态会发生变化并且未绑定到特定路线,我会改用React Context

    这是一个例子CodeSandbox With Context Example

    希望对你有帮助。

    【讨论】:

    • 我有三个表单,我使用历史将一个表单的信息传递给另一个表单,它工作正常,但是当返回到前一个表单时,我通过历史对象传递的信息变得未定义。我该如何解决。上下文 API 很好,但我该如何处理历史记录。
    • 您可能会变得未定义,因为您尚未为您所在的第一个表单设置位置状态。您将需要使用 history.replace 然后 history.push 到您的下一个表单。我更新了答案和代码框,还添加了一个代码框,其中包含将反应上下文用于持久表单的示例。无论如何,如果您有任何问题请告诉我,希望对您有所帮助。
    • 将值放入状态对象中,谢谢。
    猜你喜欢
    • 2016-09-18
    • 2018-08-07
    • 2019-03-14
    • 2020-12-07
    • 1970-01-01
    • 2016-07-05
    • 2017-08-31
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多