【发布时间】:2019-11-11 13:40:24
【问题描述】:
我在/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>
);
}
}
【问题讨论】:
-
I would like the state to be cleared to the original settings那么为什么不直接调用上下文setState并使用任何你想成为“默认状态”的东西呢? -
我尝试直接在 Route 中执行 setState 方法,但不幸的是它会创建无限循环。
标签: reactjs create-react-app react-router-dom react-context