首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >setState in handleSubmit

setState in handleSubmit
EN

Stack Overflow用户
提问于 2017-05-23 21:42:14
回答 1查看 1.6K关注 0票数 1

我有以下handleSubmit()函数,称为表单的onSubmit

代码语言:javascript
复制
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是另一个尝试对状态进行更改的函数:

代码语言:javascript
复制
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

代码语言:javascript
复制
<input type="checkbox" id="business" checked={ this.state.interests.business }
                       onChange={ (e) => this.handleChanges(e, "business") }/>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-23 23:13:18

我不确定this.setState({...this.state})是否有效,而且应该有更好的选择:

代码语言:javascript
复制
// 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传递一个回调:

代码语言:javascript
复制
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,或者只使用如下回调:

代码语言:javascript
复制
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可以是这样的:

代码语言:javascript
复制
function(newState) {
  newState.pressedEnter = true;
  // Make sure "this" is referring to the component though
  this.setState(newState);
};

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44145523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档