reactjs - 如何使用历史钩子传递数据以响应功能组件
问题描述
我正在尝试在执行 fetch 查询后实现重定向。我希望能够使用 React History 将数据传递到下一个组件(页面)。
它会是这样的:
const history = useHistory({});
/* ... */
history.push({
pathname: '/page',
state: { data: data }
})
然后在接收器中检索状态,假设接收器是基于类的组件:
this.state.data
甚至有可能用功能组件实现这样的事情吗?这个问题最干净的解决方案是什么?
感谢您的帮助
解决方案
您传递给的数据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>
}
推荐阅读
- html - 如何使用从页面左上边缘到页面右下角的 Div 或 SVG 形状制作响应式装饰样式
- excel - Excel 用公式查找和替换 - 无 VBA
- java - 对结果应用过滤器
- google-cloud-platform - 有没有办法根据 Bigquery 查询中的标签选择表?
- debugging - 使用 Anaconda Env 在 Pycharm 上进行调试
- angular - Angular 5:动态事件绑定
- javascript - Javascript 中的格式化时间、金额
- amazon-web-services - 在 Kinesis 流上发布消息是异步的吗?
- azure-java-sdk - azure java sdk 是否与 azure gov cloud 兼容?
- angular - 如何根据 jwt 令牌的到期时间戳自动注销?