繁体   English   中英

如何通过在组件之间使用 react-router-dom 来维护历史 state?

[英]how to maintain history state by using react-router-dom among components?

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

/* 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 */

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

如果我理解正确,我认为您会变得undefined ,因为反应路由器会覆盖您的课程价值。

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

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

然后您可以使用history.location.state.course;

您可能会变得不确定,因为您正在尝试将 go 恢复到第一种形式,并且尚未为该路线设置 state。 您首先需要更换 state,然后像这样推送到新表格:

// 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

注意:如果您想要 state object 特定于每条路线,则使用位置 state 来存储您的数据。 如果你有一般的 state 会改变并且不绑定到特定的路线,我会改用React Context

这是带有上下文示例的操作 CodeSandbox 示例

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM