反应路由器传递道具到路由组件

问题描述:

我正在尝试使用 react router 将 props 从我的 app.jsx 传递到我的路由组件之一,但出现以下错误

I'm trying to pass props from my app.jsx to one of my route components using react router but I get the following error

类型错误:无法读取未定义的属性acc"

TypeError: Cannot read property 'acc' of undefined

这是我的 app.jsx 中的代码:

Here's the code from my app.jsx:

<Route exact path='/FileUpload' acc={this.state.account} ethAdd={this.state.ethAddress} component={FileUpload} />

以及路由导致的组件中的代码:

And the code in the component that route leads to:

constructor(props) {
        super(props);
        this.setState({
            account: this.props.route.acc,
            ethAddress: this.props.route.ethAdd
        })
    }

通过阅读此处的其他解决方案,我真的不明白反应路由器中道具的这种传递是如何工作的,谁能帮助我了解我需要做什么?

I don't really understand from reading other solutions on here how this passing of props in react router works, can anyone help me understand what I need to do?

不会将自定义道具传递给组件.改用 渲染函数:

<Route> does not pass custom props to components. Use render function instead:

<Route exact path='/FileUpload' render={
  (props) => <FileUpload {...props} acc={this.state.account} ethAdd={this.state.ethAddress} />
} />

正如 SakoBu 提到的,你需要改变你的构造函数:

As SakoBu mentioned you need to change your constructor:

constructor(props) {
    super(props);
    this.state = {
        account: this.props.acc,
        ethAddress: this.props.ethAdd
    };
}