我的 React 应用程序中有一个组件,它是一个表单。该表单用于创建新许可证或编辑现有许可证。无论哪种方式,它都只是一个组件,它会检查 componentDidMount() 是哪个“pageType”(添加/更新)。现在我的问题是,当我使用表单编辑许可证 (licensee/:id/edit) 并单击坐浴盆按钮以创建新许可证 (licensee/add) 时,它不会重新安装零件。它将更改 URL,但所有预加载的数据仍在表单中。
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}/>