为什么setState无法按预期工作

时间:2018-12-02 02:54:49

标签: reactjs

由于某种原因,我的setState没有更新...我的回调函数甚至没有触发。我尝试将函数onSubmit()定义为onSubmit()而不是onSubmit = () =>。有任何想法吗?是的,我已经验证了我的if (milestoneBtnLabel === "Create")正在执行。

constructor(props) {
        super(props);
        this.state = {
          campus: []
        };
        this.onSubmit = this.onSubmit.bind(this);
      }

      onSubmit = e => {
        const { milestoneBtnLabel, schoolData } = this.props;
        e.preventDefault();

        if (milestoneBtnLabel === "Create") {
          this.setState(
            {
              campus: this.state.campus.concat(schoolData.schoolData.name)
            },
            () => {
              console.log("here"); <-- Doesn't execute
              this.props.saveChecklistItem({ ...this.state });
            }
          );
        }
        this.props.closeModal();
      };

2 个答案:

答案 0 :(得分:1)

也许this.props.closeModal();setState()完成之前从DOM中删除了该组件。尝试将该呼叫移至setState回调中。

if (milestoneBtnLabel === "Create") {
  this.setState(
    {
      campus: this.state.campus.concat(schoolData.schoolData.name)
    },
    () => {
      console.log("here"); <-- Doesn't execute
      this.props.saveChecklistItem({ ...this.state });
      this.props.closeModal();
    }
  );
else {
  this.props.closeModal();
}

答案 1 :(得分:0)

您的代码中有几件事需要更正

  1. 将函数声明为箭头函数时,无需手动绑定
  2. 从不建议使用concate更改数组,而应使用先前的状态将新值压入数组
  3. 此外,您还需要找到一种更好的方法来关闭模型,例如等待2秒钟然后关闭模型。因为JavaScript执行是并行的,所以您需要使对话框等待先前的操作完成。您需要考虑始终在触发提交按钮时始终关闭模态,而不仅仅是在里程碑BtnLabel ==“ Create”时

更改

     onSubmit = e => {
    const { milestoneBtnLabel, schoolData } = this.props;
    e.preventDefault();

    if (milestoneBtnLabel === "Create") {
      this.setState(
        {
          campus: this.state.campus.concat(schoolData.schoolData.name)
        },
        () => {
          console.log("here"); <-- Doesn't execute
          this.props.saveChecklistItem({ ...this.state });
        }
      );
     }
    this.props.closeModal();
     }

收件人

    onSubmit = e => {
    const { milestoneBtnLabel, schoolData, closeModal, saveChecklistItem} = this.props;
    e.preventDefault();

    if (milestoneBtnLabel === "Create" && schoolData && schoolData.schoolData){
    this.setState( prevState => (
        {
          campus: [...prevState.campus, schoolData.schoolData.name]
        }),
        () => {
          console.log("here"); <-- Doesn't execute
          saveChecklistItem({ ...this.state });
        }
      );
     }
      setTimeout(()=>{
           closeModal();
       }, 2000);
    }