【问题标题】:React Router: Replace location state then goBack, location state is undefinedReact Router:替换位置状态然后返回,位置状态未定义
【发布时间】:2020-05-08 03:35:55
【问题描述】:
this.props.history.replace({
  state: {
    from: 'dashboard'
  }
});

this.props.history.goBack();

更新this.props.location.state后使用this.props.history.goBack()this.props.location.state的值是undefined。但是

this.props.history.push({
  pathname: '/',
  state: {
    from: 'dashboard'
  }
});

有效并保留this.props.location.state 的值。

知道如何更新this.props.location.state 然后使用this.props.history.goBack

【问题讨论】:

    标签: reactjs react-router browser-history


    【解决方案1】:

    根据官方文档:

    • push(path, [state]) - (function) 将新条目推送到历史堆栈中
    • replace(path, [state]) - (function) 替换历史堆栈上的当前条目
    • go(n) - (function) 将历史堆栈中的指针移动 n 个条目
    • goBack() - (function) 等价于 go(-1)
    • goForward() - (函数) 等价于 go(1)

    如果你想使用goBack(),最好使用this.props.history.push({})

    为了更好地了解,您可以访问react-router-domhistory

    【讨论】:

    • 是的。但是使用push 代替goBack 会弄乱routing flow,因为它会将一个新条目推送到历史堆栈中,而不是删除当前条目以返回到前一个条目。
    • 我的 location.state 未定义。我在 history.replace() 中也包含了 state,它解决了我的问题。谢谢。
    猜你喜欢
    • 2021-09-07
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多