gpt4 book ai didi

javascript - 为什么state对象的名字不需要和setState中的名字一致?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:58:19 24 4
gpt4 key购买 nike

在下面的代码中,您会看到我异想天开地将我的 this.state 对象命名为“gladys”。在 handleSubmit 函数中,常量结果返回一个值,但我将此处对象的名称设置为更符合逻辑的“errormessage”。为什么这行得通?为什么在 this.state 中定义初始状态的对象的名称不必与 this.setState 更新的对象的名称相匹配? (以防万一它不明显,handleAddOption 对选项字段值运行验证并在 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>
);
}

最佳答案

之所以有效,是因为

this.state = {
gladys: undefined
}

还有这个

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

在 JavaScript 中是相等的。

所以当你这样做的时候

this.setState({ errormessage: result })

React 只是替换

errormessage: undefined

errormessage: result

您还应注意,gladys 不是州的名称,而是州的属性(property)。

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

关于javascript - 为什么state对象的名字不需要和setState中的名字一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48455219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com