退出路径后,状态重置

After exiting the path, the state is reset

我在 /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>
    );
  }
}

检查清除状态的路由将是非常紧密的耦合,最好避免。

相反,我们可以让组件 AddEmployee 清除 componentWillUnmount

上的状态

类似于:

class AddEmployee extends Component {
  componentWillUnmount {
    this.props.clearForm();
  }
}

关于定义路线:

<Route
  path="/add-employee"
  render={props => <AddEmployee {...props} clearForm={this.clearState}/>}
/>

this.clearState()中,清除您必须清除的状态值。