React - 在 React Router 中传递数据
React - Pass data in React Router
所以,我很难在两个不相关的组件之间传递数据。我有下面这段代码,但我不知道如何从其他组件接收它
<Button
className='search__button'
variant="contained"
color="primary"
size="large"
component={Link}
to={{
pathname: "/home",
state: { data: results }
}}
>
我想将变量“results”传递给一个组件,它是一个字符串映射和一个对象 Book (Map)。基本上,我的问题是,如何在 Home 组件中检索数据?
谢谢
当使用路由转换发送状态时,您可以通过几种不同的方式在接收路由的 location
对象上访问它:
对于功能组件,您可以使用 useLocation 钩子。
const { state } = useLocation();
// access state.data
如果组件由 render
、component
或 children
属性上的 Route
呈现,则 route props will be passed to the component. location
will be a prop. Or you can decorate the component with the withRouter 具有将最接近匹配 Route
的路由道具作为道具传递。
const { location: { state } } = this.props;
// access state.data
或
const { location: { state } } = props;
// access state.data
所以,我很难在两个不相关的组件之间传递数据。我有下面这段代码,但我不知道如何从其他组件接收它
<Button
className='search__button'
variant="contained"
color="primary"
size="large"
component={Link}
to={{
pathname: "/home",
state: { data: results }
}}
>
我想将变量“results”传递给一个组件,它是一个字符串映射和一个对象 Book (Map
谢谢
当使用路由转换发送状态时,您可以通过几种不同的方式在接收路由的 location
对象上访问它:
对于功能组件,您可以使用 useLocation 钩子。
const { state } = useLocation(); // access state.data
如果组件由
render
、component
或children
属性上的Route
呈现,则 route props will be passed to the component.location
will be a prop. Or you can decorate the component with the withRouter 具有将最接近匹配Route
的路由道具作为道具传递。const { location: { state } } = this.props; // access state.data
或
const { location: { state } } = props; // access state.data