在ReactJS链接中传递和访问参数
我需要在ReactJS链接中传递参数,并在链接到的组件中访问它们。这就是我所尝试的: 在在ReactJS链接中传递和访问参数,reactjs,Reactjs,我需要在ReactJS链接中传递参数,并在链接到的组件中访问它们。这就是我所尝试的: 在路由器中: <Route path="/NextComponent/:paramName" component={NextComponent}> <NextComponent/></Route> 然后在componentDidMount中: constructor(props) { super(props); console.log(props);
路由器中
:
<Route path="/NextComponent/:paramName" component={NextComponent}> <NextComponent/></Route>
然后在componentDidMount
中:
constructor(props) {
super(props);
console.log(props);
this.state = { data: [] };
}
async componentDidMount() {
const data = this.props;
this.setState({ data });
console.log(data);
console.log(this.props);
}
但是道具
是一个空对象。我试着在组件中查找其他内容,比如
console.log(this.search);
console.log(this.props.match);
console.log(this.props.location);
console.log(this.paramName);
但它们都是未定义的
我错过了什么?
警告:
优先于
和
,因此不要在同一时间使用多个
路线道具
我认为,由于这一点,您包装的子组件优先,并且没有获得路由道具
,因为您还指定了组件
。尝试不指定组件
prop和包装的子组件
<Route
path="/NextComponent/:paramName"
component={NextComponent}
>
<NextComponent/> // This one doesn't receive route-props (i.e. match, location, etc..)
</Route>
或者更简洁地使用标准的to
作为字符串
<Link to=`/NextComponent/${paramvalue}`>my link text</Link>
我的链接文本
您可以参考以访问参数。match
中有一个params
对象,您查看了吗?这是否回答了您的问题?不,这些都不行。就像我在问题中所说的,props
对象是空的@JohnRuddell,this.match
是未定义的
。好的,问题是您没有将组件连接到路由。你看过《取回路由器》了吗?谢谢@Drew。但我现在如何检索参数?如果作为道具传递,可以通过直接在组件上渲染它,或者通过路由
中的渲染
道具,或者使用withRouter
HOC装饰组件,或者使用,const{paramName}=useParams()
。
<Route
path="/NextComponent/:paramName"
component={NextComponent} // will receive route-props
/>
// or
<Route
path="/NextComponent/:paramName"
>
<NextComponent/> // needs to use hooks to access route-props
</Route>
<Link
to={{
pathname: `/NextComponent/${paramvalue}`
}}
>
my link text
</Link>
<Link to=`/NextComponent/${paramvalue}`>my link text</Link>