如何通过在组件中使用 react-router-dom 来维护历史状态?

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

我有一个用例,其中我使用 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 */

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

如果我理解正确的话,我认为你得到的是 undefined,因为 React router 覆盖了你的课程值。

将您的课程值推送到 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

希望对您有所帮助。