React-router 不会在不同的路径上重新安装组件 [英] React-router doesn't remount component on different paths
问题描述
我的 React 应用中有一个组件,它是一个表单.该表单用于创建新许可证或编辑现有许可证.无论哪种方式,它都只是一个组件,它会检查 componentDidMount() 是哪个pageType"(添加/更新).现在我的问题是,当我使用表单编辑许可证 (licensee/:id/edit) 并单击坐浴盆按钮以创建新许可证 (licensee/add) 时,它不会重新安装成分.它将更改 URL,但所有预加载的数据仍在表单中.
I have a component in my react app which is a form. The form is used to create new licenses OR edit existing licenses. Either way it is only one component and it checks on componentDidMount() which "pageType" (add/update) it is. Now to my problem, when I'm using the form to edit a license (licensee/:id/edit) and I’m clicking the button which is bidet to create a new license (licensee/add), it will not remount the component. It will change the URL but all the preloaded data is still in the form.
LicenseeForm = Loadable({
loader: () => import('./license/LicenseeForm'),
loading: 'Loading..'
});
render() {
return (
<Router>
<Switch>
<LoginRoute exact path="/" component={this.LoginView}/>
<LoginRoute exact path="/login" component={this.LoginView}/>
<PrivateRoute exact path="/licensees/add" component={this.LicenseeForm}/>
<PrivateRoute exact path="/licensees/:id/update" component={this.LicenseeForm}/>
<Route path="*" component={this.NotFoundPage}/>
</Switch>
</Router>
)
}
const PrivateRoute = ({component: Component, ...rest}) => (
<Route
{...rest}
render={props =>
authService.checkIfAuthenticated() ? (<Component {...props} />) :
(<Redirect
to={{
pathname: "/login",
state: {from: props.location}
}}/>
)
}
/>
);
组件:
componentDidMount() {
const locationParts = this.props.location.pathname.split('/');
if (locationParts[locationParts.length-1] === 'add') {
this.setState({pageType: 'add'});
} else if (locationParts[locationParts.length-1] === 'update') {
this.setState({pageType: 'update'});
...
}}
编辑
现在是这样的:
<PrivateRoute exact path="/licensees/add" key="add" component={this.LicenseeForm}/>
<PrivateRoute exact path="/licensees/:Id/update" key="update" component={this.LicenseeForm}/>
推荐答案
如果您确实需要在路由更改时重新挂载组件,您可以将唯一键传递给组件的键属性(键与您的路径/路由相关联).所以每次路由改变,key也会改变,触发React组件卸载/重新挂载.
If you do need a component remount when route changes, you can pass a unique key to your component's key attribute (the key is associated with your path/route). So every time the route changes, the key will also change which triggers React component to unmount/remount.
这篇关于React-router 不会在不同的路径上重新安装组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!