我有两个链接可以获取示例组件,但是当我单击其中的任何一个时,它都会被加载;当我单击另一个链接时,它不会重新呈现,只有url被更改。我想在两次链接单击时都重新呈现该组件。有什么办法吗?
当我在进行React项目时,有时会遇到类似的问题。
您需要在 组件 中使用 componentWillReceiveProps 函数。
componentWillReceiveProps(nextProps){ //call your api and update state with new props }
更新
对于React 16.3+版本,请使用 componentDidUpdate
componentDidUpdate
componentDidUpdate (prevProps, prevState) { // update state }
通过调用url www.example.com/content/a可以更清楚地了解何时首次加载组件 componentDidMount()。
componentDidMount()
现在,当您单击另一个链接时,说www.example.com/content/b,将调用相同的组件,但是这次prop发生了变化,您可以访问此新的prop,在componentWillReceiveProps(nextProps)该prop下 可以调用api并获取新数据。
componentWillReceiveProps(nextProps)
现在,您可以说一个常用函数initializeComponent()并从componentDidMount()和调用它componentWillReceiveProps()
initializeComponent()
componentWillReceiveProps()
您的路由器看起来像这样:
ReactDOM.render(( <Router history={browserHistory}> <Route path="/content" component={app}> <IndexRoute component={home}/> <Route path="/content/:slug" component={component_name} /> </Route> </Router> ), document.getElementById('app'));
因此,现在当您致电www.example.com/content/a时, a 将被视为。在该组件内,如果您调用www.example.com/content/b,则 b 将被视为子弹,并且可以作为componentWillReceiveProps中的nextProps参数使用。
希望能帮助到你!!