【问题标题】:React: location.state is undefined on first time navigating after page loadReact:在页面加载后第一次导航时未定义 location.state
【发布时间】:2018-10-16 09:20:35
【问题描述】:

我有一个 React 组件,它显示一个链接:

Magic.tsx:

const { message } = this.props;
<Link to={ { pathname: HOGWARTS, state: { message } } }>
  Go to Page
</Link>

我将这个 Magic 组件作为 Prop 传递给另一个组件,在那里我使用动态 message 状态对其进行迭代

Parent.tsx

const CustomComp = this.props.Magic;
const content = messageArray.map(msg => <CustomComp message={ msg } />)
{ content } //Render all the Links with message state

这是正确呈现链接。但是当我点击链接并调试HOGWARTS 页面时,location.state 是未定义的。 如果返回上一页,再次点击,location.state 是正确的,有message 数据。 所以不知何故它在页面加载时不起作用,但在第二次点击后,它就起作用了。

有人遇到过同样的问题吗?

注意:我已经使用React Devtool 检查了&lt;Link /&gt; 标记,在侧边栏它显示,message 状态附加到此链接。

【问题讨论】:

    标签: javascript reactjs react-router location


    【解决方案1】:

    'state'匹配'BrowserRouter','hash'匹配'HashRouter',所以如果你使用'HashRouter'匹配'hash','state'必须是未定义的

    【讨论】:

      【解决方案2】:

      你只需要处理你的状态: { message } undefined case like below ,因为只有当链接被点击时状态才可用

      所以location.state 在初始时是未定义的。

      在你的 Parent.tsx 中

      你可以做这样的事情..

      const message =
                  (this.props.location.state && this.props.location.state.message) != undefined
                      ? this.props.location.state.message
                      : " ";
      

      然后使用它

      const content = messageArray.map(msg => <CustomComp message={ msg } />)
      

      这应该可以帮助你.. :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-14
        • 1970-01-01
        • 2019-07-25
        • 1970-01-01
        • 2020-07-08
        • 1970-01-01
        • 2011-10-22
        • 1970-01-01
        相关资源
        最近更新 更多