当组件挂载时,我有一个带有datatable获取数据的路由页面。当我多次单击相同的react router(到上面的路由)时,似乎只有在路由更改时才卸载组件(要呈现不同的组件)。
我希望当再次单击相同的链接以获取新数据时,组件被强制重新装入。是否有任何选项在反应-路由器-多玛链接或任何其他链接组件或任何技巧来做到这一点?
我这里的示例代码:https://codesandbox.io/s/react-router-9wrkz
我希望当多次单击“关于链接”时,有关组件将重新装入。
发布于 2019-09-04 03:22:19
强制组件重新挂载的一种方法是更改key
支柱(可以使用Date.now()
或props.location.key
):
<Route
path="/about"
render={props => <About key={props.location.key} {...props} />}
/>
发布于 2019-09-04 04:09:10
您可以使用此方法来呈现
componentWillReceiveProps(recievedProps) {
console.log("componentWillReceiveProps called");
if (
recievedProps &&
this.props &&
recievedProps.location &&
this.props.location &&
recievedProps.location.key &&
this.props.location.key &&
recievedProps.location.key !== this.props.location.key
) {
this.setState({ loading: true });
promise().then(result => {
this.setState({ value: result, loading: false });
});
}
}
发布于 2021-07-28 05:20:51
将来可以用来作参考。除了上面提到的答案之外,我还需要调整一些东西,因为它们都不像我想要的那样工作。前面提到过比较道具,但是因为键在对象(引用)中,所以它从未看到更新(您正在比较同一个对象)。所以我把它作为道具保存下来。
我更喜欢使用componentDidUpdate,因为当您可能只需要更新某些元素时,没有卸载和挂载整个组件,
在本例中,您的组件确实需要使用withRouter()进行链接,这样您就可以访问路由支持。
// You cant use prevProps because object will be the same, so save it in component
private currentRouteLocationKey: string| undefined;
public componentDidUpdate(): void {
const currentRouteKey = this.props.history.location.key;
// Compare keys so you only update when needed
if (this.currentRouteLocationKey !== currentRouteKey) {
// Add logic you want reset/ updated
this.refreshPage();
// Save the new key
this.currentRouteLocationKey = currentRouteKey;
}
}
https://stackoverflow.com/questions/57786965
复制