我看过很多问题,但没有得到答案。 当我在'/dashboard'
时做history.push('/user')
时,它工作得很好,因为我的基本路线不同,即user!=dashboard
。但是当我在'/user'
号公路上时,现在我想去history.push('/user/87')
.这里发生了奇怪的事情,因为基本路由与user===user
相同,我的网址发生了变化,但我的组件没有再次渲染。我已经使用了 react-router-dom 提供的<Link>
的东西,但它也不起作用。
这是我的根本东西,
import { BrowserRouter } from 'react-router-dom'; //"^5.0.1"
ReactDOM.render((
<Provider store={store}>
<BrowserRouter>
<AppContainer />
</BrowserRouter>
</Provider>
), document.getElementById('root'));
请提供解决方案,这将有很大帮助。
我和同事发现了一个技巧,我们可以使用getDerivedStateFromProps
和componentDidUpdate
生命周期
state = {
currentUrl: this.props.match.url,
}
static getDerivedStateFromProps(props, state) {
let updatedState = {};
if (props.match.url !== state.currentUrl) {
updatedState.currentUrl = props.match.url;
}
return updatedState;
}
componentDidUpdate(prevProps) {
if (prevProps.match.url !== this.state.currentUrl) {
// re-initiate your state so that it can run your render lifecycle
this.setInitialState();
}
}
我们还可以通过在第二个参数中提供[this.props.match.url]
来使用useEffect钩子,以便在您的 url 更新时可以设置您的状态。
也许在推送或使用 :p arams 后立即执行 this.forceUpdate((