首页 > 解决方案 > 如何使用历史钩子传递数据以响应功能组件

问题描述

我正在尝试在执行 fetch 查询后实现重定向。我希望能够使用 React History 将数据传递到下一个组件(页面)。

它会是这样的:

 const history = useHistory({});
 /* ... */
 history.push({
       pathname: '/page',
       state: { data: data }
 })

然后在接收器中检索状态,假设接收器是基于类的组件:

this.state.data

甚至有可能用功能组件实现这样的事情吗?这个问题最干净的解决方案是什么?

感谢您的帮助

标签: reactjsreact-routerstatereact-hooksreact-functional-component

解决方案


您传递给的数据history.push本质上并不像这样绑定到类组件,因此对于类或功能组件,您必须从某处访问位置状态,然后将其分配给组件的状态

如果功能组件是从路由呈现的,它应该history作为道具接收,然后您可以通过简单地执行类似history.location.state. 然后你可以用它做任何你想做的事情并将它分配给状态通过useState

我想你也可以使用那个钩子useHistory来获取位置状态。

就像是

function MyComponent() {
  const history = useHistory()

  return <div>
    {JSON.stringify(history.location.state)}
  </div>
}

// Rendered via <Route component={MyOtherComponent} />

function MyOtherComponent({ history }) {
  return <div>
    {JSON.stringify(history.location.state)}
  </div>
}

推荐阅读