问题描述
当两个路由使用相同的组件时,如何在路由更改时重新安装组件?
How can I re-mount a component on route change when using the same component for both the routes?
这是我的代码.
routes.jsx
<Router history={browserHistory}>
<Route path="/" component={Home} />
<Route path="/foo/:fooId" component={Home} />
</Router>
我在 Home
组件中对 fooId
进行了条件检查,从而相应地呈现 JSX.
I have a conditional check in Home
component for fooId
, which renders the JSX accordingly.
<Link to="/foo/1234">fooKey</Link>
目前,当点击 fooKey
时,路由发生变化,Home 组件中的渲染功能会重新触发,但不会再次挂载.
At the moment, when clicked on fooKey
the route changes and the render function in Home component is re-triggered but is not mounted again.
我浏览了其他提到 componentWillReceiveProps
的答案,但我在 constructor
中有很多配置,我不想将所有这些配置移动到componentWillReceiveProps
.
I went through other answers which mentioned componentWillReceiveProps
, but I have a lot of config in the constructor
and I don't want to be moving all of that config to componentWillReceiveProps
.
如果需要更多信息,请发表评论.
Please comment if more information is needed.
推荐答案
如果您需要在每次路由匹配时强制重新安装组件,您可以通过 key 属性实现它,除非您知道什么你在做什么:
If you need to force remounting a Component on every routing match you could achieve it by the key property unless you're knowing what you're doing:
<Route
exact
path={'some path'}
render={props => <RemountAlways key={Date.now()} {...props} />}
/>
key={Date.now()}
这个关键属性会强制每次都重新挂载.
key={Date.now()}
this key property will force react to remount every time.
注意: componentWillReceiveProps 在 React 中是个坏消息.
Note: componentWillReceiveProps is bad news in react.
这篇关于在路线改变时反应力重新安装组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!