从redux道具反应形式更新状态

时间:2018-05-26 11:54:12

标签: reactjs redux

我有一个组件,通过redux从它的父母那里接受道具。这是一个多步骤表单,因此用户可以返回此部分并更新表单输入字段。但是,当我回到该部分并尝试清除该值时,由于getDerivedStateFromProps的设置方式,它会使用旧值填充它。

所以,基本上,如果我输入的值为'Test',则无法完全删除它。

    class StepOne extends Component {
  static getDerivedStateFromProps = (nextProps, prevState) => {
    const {
      stepOne: { name, location, description }
    } = nextProps;
    const shouldUpdate = name === prevState.name || prevState.name === '';
    return shouldUpdate ? { name } : null;
  };

  state = {
    name: '',
    location: '',
    description: ''
  };

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

  handleNext = (e) => {
    e.preventDefault();
    const { name, description, location } = this.state;
    this.props.setStepOne({ name, location, description });
  };

  render() {
    return (
      <Col xs={{ size: 8, offset: 2 }}>
        <Col xs='12' className='margin-bottom-60'>
          <label className='header-label' htmlFor='name'>
            Name
          </label>
          <input
            className='form-input'
            placeholder='Whats the conference name?'
            id='name'
            name='name'
            defaultValue={this.props.stepOne.name !== '' ? this.props.stepOne.name : null}
            value={this.state.name}
            onChange={this.handleChange}
          />
        </Col>
        <Col xs='12' className='margin-bottom-60'>
          <label className='header-label' htmlFor='location'>
            Location
          </label>
          <input
            className='form-input'
            placeholder='Where is the conference located?'
            id='location'
            name='location'
            value={this.state.location}
            onChange={this.handleChange}
          />
        </Col>
        <Col xs='12' className='margin-bottom-60'>
          <label className='header-label' htmlFor='description'>
            Description
          </label>
          <input
            className='form-input'
            placeholder='Tell us something more about the conference...'
            type='textarea'
            id='description'
            name='description'
            value={this.state.description}
            onChange={this.handleChange}
          />
        </Col>
        <div
          style={{
            width: '100%',
            position: 'fixed',
            bottom: '0px',
            zIndex: '100',
            textAlign: 'center',
            padding: '10px',
            left: '0px'
          }}
        >
          <NextButton handleClick={this.handleNext} />
        </div>
      </Col>
    );
  }
} 

1 个答案:

答案 0 :(得分:1)

为什么不用道具初始化州?我假设它们具有与本地状态相同的初始值。

state = {
  name: this.props.stepOne.name,
  location: this.props.stepOne.location,
  description: this.props.stepOne.description
};

或更简洁:

state = { ...this.props.stepOne }

然后你根本不需要getDerivedStateFromProps

相关问题