【问题标题】:Dynamic update the setState (Object) in React在 React 中动态更新 setState(Object)
【发布时间】:2020-10-31 17:05:07
【问题描述】:

我有一个状态

 constructor(props) {
        super(props);
        this.state = {
          qualification: {
            fieldOfStudy: "Architecture",
            degree: "",
          }
        };
      }

我想在函数调用时动态更新状态值

onChange={this.handleChangeObj("qualification")}

这是我写的函数:

handleChangeObj = (ObjName) => ({ target }) => {

//String Value - Qualification
console.log("handleChangeObj -> ObjName", ObjName);

//fieldOfStudy: Architecture
    console.log((target.name + ":" + target.value));

// Doubt over here how to update the value for qualification.fieldOfStudy : Architecture
    this.setState(() => ({
      ...this.state.ObjName,
      [target.name]: [target.value],
    }));

    // this is not working.
this.setState({ [ObjName.target.name]: target.value });
  };

【问题讨论】:

    标签: javascript reactjs object setstate


    【解决方案1】:

    第一个参数被传递给外部函数,所以你需要做的就是在括号中引用它:

    this.setState({
      [ObjName]: {
        ...this.state[ObjName],
        [target.name]: [target.value]
      }
    });
    

    【讨论】:

    • 我收到此错误 Uncaught TypeError: ObjName.target is undefined 以上解决方案对我不起作用。可以提出替代方案。
    • ObjName.target 在我的代码中的任何地方都没有使用。确保准确复制它,例如:[target.name]: [target.value]。目标不是ObjName 的属性,它是一个独立变量。
    猜你喜欢
    • 1970-01-01
    • 2020-03-03
    • 2020-01-16
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    相关资源
    最近更新 更多