【问题标题】:Proper way of clearing forms without redux-form没有redux-form清除表单的正确方法
【发布时间】:2016-02-19 11:06:37
【问题描述】:

这是我的表格

<form className="input-group" onSubmit={this.handleSubmit}>
  <input className="form-control"
   type="text"
   placeholder="Insert name"
   autofocus="true" />
   <span className="input-group-btn">
     <button type="submit" className={classNames}>Add</button>
   </span>
</form>

这是我的事件处理程序:

handleSubmit(e) {
 e.preventDefault();
 let name = e.target[0].value;
 if (name.length > 0) {
  this.props.dispatch(createClassroom(name));
 }
}

我的问题是:

提交后清除表单的正确“redux 方式”是什么? 我需要调度不同的操作还是应该使用现有的createClassroom 操作?

注意:我宁愿不使用 redux-form 包。

【问题讨论】:

  • 看起来你不是在使用受控输入,你怎么能通过调度动作来清除它?

标签: forms reactjs redux


【解决方案1】:

首先,您必须确保&lt;input&gt;controlled component,方法是从状态中传递其各自的值:

const { classroom } = this.props;

// in return:
<input type="text" value={ classroom.name } />

然后,理想情况下,可以通过提交 RESET 操作来清除表单,您的 classroom 减速器会执行该操作:

const initialState = {};

function classroomReducer(state = initialState, action) {
  switch (action.type) {
    // ...
    case 'RESET_CLASSROOM':
      return initialState;
    default:
      return state;
  }
}

【讨论】:

  • 事后看来,我的问题表述得不是很好。但是,您的回答有所帮助,谢谢。
猜你喜欢
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
  • 2013-08-24
  • 2019-08-31
  • 1970-01-01
相关资源
最近更新 更多