我正在将表单引入/add-employee
路径,该路径将数据捕获到主App.js文件中。填写完字段后,更改路径,我希望将状态清除为原始设置。
我试图输入另一个<Route>
来捕获位置,并且如果它是/add-employee
状态以外的路径,则会被更改,但这会导致无限循环
以add-employee
方式添加雇员。提交表单后,员工将显示在/employees
路径中。
//App.js
class App extends Component {
state = {
employeesList: [],
id: 0,
firstName: '',
lastName: '',
email: '',
phone: '',
accountNumber: '',
rate: '',
location: '',
};
render() {
const contextElements = {
...this.state,
handleDate: this.handleDate,
handleSubmit: this.handleSubmit,
};
return (
<Router>
<AppContext.Provider value={contextElements}>
<div className="app">
<Navigation />
<Footer />
<div className="content">
<Switch>
<Route path="/" exact component={InstructionPage} />
<Route
path="/add-employee"
component={AddEmployee}
render={props => console.log(props.location.pathname)}
/>
<Route path="/employees" component={Employees} />
<Route path="/ranking" component={Ranking} />
<Route component={ErrorPage} />
</Switch>
</div>
</div>
</AppContext.Provider>
</Router>
);
}
}
答案 0 :(得分:0)
检查路线以清除状态将是非常紧密的耦合,因此最好避免。
相反,我们可以让组件AddEmployee
清除componentWillUnmount
上的状态
类似的东西:
class AddEmployee extends Component {
componentWillUnmount {
this.props.clearForm();
}
}
在定义路线时:
<Route
path="/add-employee"
render={props => <AddEmployee {...props} clearForm={this.clearState}/>}
/>
在this.clearState()
中,清除所需的状态值。