React Router v4中如何向路由组件传递Props?
给路由组件传递自定义props的几种方法
嘿,这个问题我太熟了!要让SomeComponent能通过this.props.xxx拿到你传递的数据,有几个实用的方法,我给你一步步讲清楚:
1. 用render方法传递(最推荐)
把Route里的component换成render,这样你可以灵活地给组件传入自定义props,还能顺便把路由自带的props(比如history、location、match)也传过去,不会丢失:
import SomeComponent from './SomeComponent'; import { Router, Route } from 'react-router-dom'; // ... <Router> <Route path='/' render={(routeProps) => ( <SomeComponent {...routeProps} // 保留路由原生props customMessage="这是给组件的自定义数据" user={{ name: '张三', role: 'admin' }} /> )} /> </Router>
之后在SomeComponent里,你就可以直接通过this.props.customMessage或者this.props.user拿到数据,同时this.props.history这些路由相关的方法也能正常使用。
2. 直接在component属性里包装(不推荐,有性能坑)
如果你一定要用component属性,也可以直接返回组件并传入props,但要注意:这种方式每次渲染都会创建新的组件实例,可能导致不必要的重渲染,所以一般不推荐:
<Router> <Route path='/' component={(props) => ( <SomeComponent {...props} customData="测试数据" /> )} /> </Router>
3. 通过URL动态参数传递(适合从URL取数据)
如果你的数据是和URL路径相关的(比如用户ID、商品ID),可以用路由的动态参数:
<Router> <Route path='/user/:userId' component={SomeComponent} /> </Router>
在SomeComponent里,你可以通过this.props.match.params.userId拿到URL里的userId值:
class SomeComponent extends React.Component { componentDidMount() { console.log('用户ID:', this.props.match.params.userId); } // ... }
这些方法里,render方式是最稳妥也最灵活的,既能满足自定义数据传递,又不会破坏路由的原生功能~
内容的提问来源于stack exchange,提问作者user818700
相关产品推荐
相关产品推荐

