【发布时间】:2018-05-26 11:54:12
【问题描述】:
我有一个组件通过 redux 接受来自它的父级的 props。这是一个多步骤表单,因此用户可以返回此部分并更新表单输入字段。但是,当我回到该部分并尝试清除该值时,由于 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>
);
}
}
【问题讨论】:
-
我可能误解了你的目标,但不应该是
const shouldUpdate = name !== prevState.name吗? -
我无法更新表单输入值。基本上,如果我输入“测试”然后继续下一步并返回到该组件,即
Test应该预先填充到表单中,我应该能够清除整个字符串以更新它