反应:位置状态在页面加载后第一次导航时未定义



我有一个 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 是正确的,具有message数据。 所以不知何故它不适用于页面加载,但在第二次单击后,它可以工作。

有人遇到同样的问题吗?

注意:我已经使用React Devtool检查了<Link />标签,在侧边栏上它显示了附加到此链接message状态。

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

你只需要处理你的状态:{ message } 未定义的情况,如下所示,因为该状态仅在单击链接时可用

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

在你的家长.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 } />)

这应该对你有所帮助..:)

最新更新