我正在尝试使用React Router将props从app.jsx传递到我的路由组件之一,但是出现以下错误
TypeError:无法读取未定义的属性'acc'
这是我app.jsx中的代码:
<Route exact path='/FileUpload' acc={this.state.account} ethAdd={this.state.ethAddress} component={FileUpload} />
以及路由中导致该组件的代码:
constructor(props) {
super(props);
this.setState({
account: this.props.route.acc,
ethAddress: this.props.route.ethAdd
})
}
我在这里阅读其他解决方案并不能真正理解反应路由器中道具传递的工作原理,有人可以帮助我理解我需要做什么吗?
答案 0 :(得分:5)
<Route>
不会将自定义道具传递给组件。请改用render function:
<Route exact path='/FileUpload' render={
(props) => <FileUpload {...props} acc={this.state.account} ethAdd={this.state.ethAddress} />
} />
正如SakoBu所述,您需要更改构造函数:
constructor(props) {
super(props);
this.state = {
account: this.props.acc,
ethAddress: this.props.ethAdd
};
}
答案 1 :(得分:5)
以下是将道具传递到路线组件的几种方法。
使用react-router v5,我们可以通过使用<Route>
组件包装来创建路线,以便我们可以轻松地将prop传递给所需的组件,像这样。
<Route path="/">
<Home name="Sai" />
</Route>
类似地,您可以在v5中使用儿童道具。
<Route path="/" children={ <Home name="Sai" />} />
如果您使用react-router v4,则可以使用渲染道具传递它。
<Route path="/" render={() => <Home name="Sai" />} />