react:location.state 在页面加载后第一次导航时未定义

IT技术 javascript reactjs react-router location
2021-04-29 05:33:35

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

魔术.tsx:

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

我将此Magic组件作为 Prop传递给另一个组件,在那里我使用 Dynamicmessage状态迭代它

父.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数据。所以不知何故它在页面加载时不起作用,但在第二次点击后,它起作用了。

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

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

2个回答

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

你只需要处理你的 state: { 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 } />)

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