退出路径后,状态将重置

时间:2019-06-30 16:47:24

标签: reactjs create-react-app react-router-dom react-context

我正在将表单引入/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>
    );
  }
}

1 个答案:

答案 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()中,清除所需的状态值。