handleSubmit中的setState

时间:2017-05-23 21:42:15

标签: reactjs single-page-application jsx setstate

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

1 个答案:

答案 0 :(得分:0)

我不确定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);
};

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