我很难理解在这里设计路由。例如 -
array.map((each)=>(
<Link to="details/${each.id}"> <Card props={each}/> </Link>
))
通过点击这些卡片,详细页面的骨架将打开,但我如何将与卡片相关的一些数据传递到新页面?我想发一些 api数据到与每张卡片相关的新页面或传递一些 资讯在切换到该新组件页面后调用与该卡相关的 api。
最佳答案
使用路由转换发送数据
您可以使用 Link
发送状态以及路由转换。的to object .
to: object
An object that can have any of the following properties:
- pathname: A string representing the path to link to.
- search: A string representation of query parameters.
- hash: A hash to put in the URL, e.g. #a-hash.
- state: State to persist to the location. <-- you need this
array.map((each)=>(
<Link
to={{
pathname: `details/${each.id}`,
state: {
// whatever you need to send with the route transition
},
}}
>
<Card props={each}/>
</Link>
))
接收路由状态你有几个选择。
const { state } = useLocation();
如果你的组件用
withRouter
装饰它将当前路由 Prop 作为 Prop 注入(inject)。 export default withRouter(EachComponent);
访问 state
来自 location
支柱。 const { state } = this.props.location;
Route
直接渲染组件并接收 route props .如果你的组件是由
Route
直接渲染的它将传递给它的路线 Prop 。 <Route path="/details/:id" component={EachComponent} />
访问 state
来自 location
支柱。 const { state } = this.props.location;
注:路由状态是 transient 的,这意味着它只存在于从一个路由到下一个路由的转换过程中。如果您直接导航到接收路由,它将没有状态,因为它没有使用来自提供状态的路由的转换。
关于reactjs - React 路由器 - 将 api 数据传递给链接的组件以使用新页面打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66609972/