【发布时间】:2023-04-11 04:46:01
【问题描述】:
我的反应应用程序中有一个组件,它是一个表单。该表格用于创建新许可证或编辑现有许可证。无论哪种方式,它都只是一个组件,它会检查 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}/>
【问题讨论】:
-
由于 react 路由器和 React 的工作方式,我认为您将需要使用 shouldcomponentUpdate...github.com/ReactTraining/react-router/blob/master/packages/…
-
"当位置发生变化时,
没有检测到任何prop或状态变化,所以它的子组件不会被重新渲染。"
标签: javascript reactjs react-router components