更新reactjs中的嵌套状态

时间:2018-08-12 12:45:39

标签: reactjs

我有一个状态类似的组件。我正在创建动态表单,但一切正常,但是一旦单击提交按钮,我想重置表单值。 为此,我有一个名为 resetForm()的辅助函数,但不幸的是,该逻辑无法正常工作。 有人可以帮忙吗?

state = {
    expenseForm: {
        date: {
            elementType: 'input',
            elementConfig: {
                type: 'date',
                placeholder: 'Enter Date..'
            },
            value: '',
            validation: {
                required: true,
                isDate: true
            },
            valid: false,
            touched: false
        },
        category: {
            elementType: 'select',
            elementConfig: {
                options: !this.props.loading ? transformCategory(this.props.categories): null
            },
            value: transformCategory(this.props.categories)[0].value,
            validation: {
                required: true,
                minLength: 4
            },
            valid: true,
            touched: false
        },
        description: {
            elementType: 'input',
            elementConfig: {
                type: 'text',
                placeholder: 'Enter Description..'
            },
            value: '',
            validation: {
                required: true,
                minLength: 6
            },
            valid: false,
            touched: false
        },
        amount: {
            elementType: 'input',
            elementConfig: {
                type: 'number',
                placeholder: 'Enter amount..'
            },
            value: '',
            validation: {
                required: true,
                minLength: 1
            },
            valid: false,
            touched: false
        }
    },
    formIsValid: false
}

React Component code link

1 个答案:

答案 0 :(得分:1)

您可能有一个函数getInitialState,该函数返回可以用作组件初始状态的对象。当您需要重置组件状态时,可以再次将setStategetInitialState一起使用。

示例

function getInitialState() {
  return {
    email: "",
    password: ""
  };
}

class App extends React.Component {
  state = getInitialState();

  onChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  resetForm = () => {
    this.setState(getInitialState());
  };

  render() {
    const { email, password } = this.state;

    return (
      <div>
        <div>
          Email: <input name="email" value={email} onChange={this.onChange} />
        </div>
        <div>
          Password: <input name="password" type="password" value={password} onChange={this.onChange} />
        </div>
        <button onClick={this.resetForm}> Reset </button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>