2017-10-04 88 views
0

我正在将一个应用程序(不是我写的)从react-router v2迁移到v4。将react-router v2迁移到v4 onEnter参数

老v2的代码如下所示:

<Route path="/configurations/:id" onEnter={loadConfiguration}> 
    // some stuff 
</Route> 

新的V4代码如下所示:

<Route path="/configurations/:id" component={MyComponent}> 
    // some stuff 
</Route> 

export default class MyComponent extends Component { 
    componentDidMount() { 
    loadConfiguration() 
    } 
    // render method, etc 
} 

的问题是,在V2的loadConfiguration函数调用3个PARAMS - nextState ,替换,回调

在v4代码中,用0个参数调用loadConfiguration函数。

从v2迁移到v4时,如何将相同的值传递给loadConfiguration?

回答

1

您可以使用渲染道具传递给您的组件:

<Route path="/configurations/:id" render={ 
() => <MyComponent nextState={ nextState } replace={ replace } callback={ callback } /> 
} /> 

然后在您的组件:

export default class MyComponent extends Component { 

    loadConfiguration() { 
    ... 
    } 

    componentDidMount() { 
    this.loadConfiguration(this.props.example, this.props.replace, this.props.callback) 
    } 

    // render method, etc 

} 

你也可以从父传下loadConfiguration功能作为道具,如果需要的话,然后在你的组件中调用它为this.props.loadConfiguration()


注:

<Route path="/configurations/:id" render={ 
    (props) => <MyComponent example={ props.example } /> 
} /> 
:你也可以从父传道具