首页 文章

为什么状态对象的名称不需要与setState中的名称匹配?

提问于
浏览
3

在下面的代码中,你会看到我异想天开地命名我的this.state对象'gladys' . 在handleSubmit函数中,const结果返回一个值,但是我在这里将对象的名称设置为更符合逻辑的'errormessage' . 为什么这样做?为什么在this.state中定义其初始状态的对象的名称不必与this.setState更新的对象的名称相匹配? (以防万一不显而易见,handleAddOption对optionfield值运行验证,如果newoption等于空字符串或已经存在,则返回错误消息 . )

class AddOption extends React.Component {
constructor(props){
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = {
        gladys: undefined
    }
}
handleSubmit(e) {
    e.preventDefault();
    const newoption = e.target.elements.optionfield.value.trim();
    const result = this.props.handleAddOptions(newoption);
    e.target.elements.optionfield.value = '';

    this.setState((prevState) => ({ 
        errormessage: result
    }));
}
render () {
    return (
        <div>
        {this.state.errormessage && <p>{this.state.errormessage}</p>}
        <form onSubmit={this.handleSubmit}>
        <input type='text' name='optionfield'/>
        <button>Add an Option</button>
        </form>
        </div>
    );
}

}

2 回答

  • 4

    它的作用是因为这个

    this.state = {
        gladys: undefined
    }
    

    还有这个

    this.state = {
        gladys: undefined,
        errormessage: undefined
    }
    

    在JavaScript中是相同的 .

    所以,当你这样做

    this.setState({ errormessage: result })
    

    React只是替换

    errormessage: undefined
    

    errormessage: result
    

    您还应注意 gladys 不是州的名称,而是州的 property .

    组件的状态可以包含多个属性,例如 gladyserrormessage .

  • 1

    这是可能的,因为 setState 浅层地将返回的对象与状态对象合并,此行为允许对状态进行部分更新,例如示例中的状态 .

    // Let's say that the current state looks like this
    this.state = { someProp: 'someValue', anotherProp: 'anotherValue' };
    
    // Calling set state like this
    this.setState((prevState) => ({ 
        errormessage: 'result'
    }));
    
    // Means that you are merging the prevState, shown above, into a new
    // State object wich will contain the errormessage prop
    this.state = { 
        someProp: 'someValue', 
        anotherProp: 'anotherValue',
        errormessage: 'result',
    };
    

    这是official documentation关于 setState 的链接

相关问题