我有以下handleSubmit()函数,称为表单的onSubmit:
handleSubmit = (e) => {
e.preventDefault()
console.log(JSON.stringify(this.state))
if(this.validateForm())
this.props.history.push("/work?mins="+this.state.minutes+"&interest="+this.interestsInitials())
// the following line breaks everyhting
this.setState({...this.state, pressedEnter: true})
}validateForm是另一个尝试对状态进行更改的函数:
handleChanges = (e, changeName) => {
switch (changeName) {
case "minutes":
this.setState({...this.state, minutes: e.target.value})
break
case "business":
this.setState({...this.state, interests:{...this.state.interests, business: e.target.checked} })
break
// ...
default:
console.log("Cannot identify the input")
}
}我担心的是,把setState打得这么近会破坏一切。这是真的吗?
注意,在以下标记中调用了handleSubmit:
<input type="checkbox" id="business" checked={ this.state.interests.business }
onChange={ (e) => this.handleChanges(e, "business") }/>发布于 2017-05-23 23:13:18
我不确定this.setState({...this.state})是否有效,而且应该有更好的选择:
// Only pass new changes
this.setState({ minutes: e.target.value });
// When things get a bit nested & messy
const interests = this.state.interests; // Might need to clone instead of direct assignment
interests.business = e.target.checked;
this.setState({ interests });您还可以像这样向setState传递一个回调:
this.setState({ minutes: e.target.value }, () => {
// this callback is called when this setState is completed and the component is re-rendered
// do more calculations here & safely set the new state changes
const newState = { minutes: 12 };
this.setState(newState);
});为了避免如此密切地调用setState,可以让validateForm以对象的形式返回状态更改,将pressedEnter: true扩展到对象,然后为所有更改调用一个最终的setState,或者只使用如下回调:
handleChanges = (e, changeName, cb) => {
const newState = this.state; // Might need to clone instead of direct assignment
switch (changeName) {
case "minutes":
newState.minutes = e.target.value; break;
case "business":
newState.interests.business = e.target.checked; break;
//...
default:
console.log("Cannot identify the input"); break;
}
cb(newState);
}cb可以是这样的:
function(newState) {
newState.pressedEnter = true;
// Make sure "this" is referring to the component though
this.setState(newState);
};如果事情变得太混乱,只需将上面的回调转换为组件的方法即可。
https://stackoverflow.com/questions/44145523
复制相似问题