【问题标题】:After exiting the path, the state is reset退出路径后,状态被重置
【发布时间】: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


【解决方案1】:

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

相反,我们可以让组件AddEmployee 清除componentWillUnmount 上的状态

类似:

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

关于定义路线:

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

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

【讨论】:

    猜你喜欢
    • 2016-10-21
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多