handleSubmit中的setState

setState in handleSubmit

我有以下 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") }/>

我不确定 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(s),您可以让 validateForm return 状态以对象的形式变化,扩展 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);
};

如果事情变得太混乱,只需将上面的回调转换为组件的方法即可。