首页 > 解决方案 > 如何将状态值分配给另一个对象?

问题描述

我已经尝试了下面的所有内容。
它不工作有什么原因吗?
有什么建议吗?
感谢您的友好回复。

addInfo = () => {
  const hash = this.state.hash;
  //test if all required fields are provided
  if (this.state.firstName && this.state.lastName) {
    allMap[hash] = Object.assign(this.state);
    /*
    tried these too
    allMap[hash] = Object.assign({}, this.state);
    allMap[hash] = {...this.state};
    allMap[hash] = this.state
    */
    this.reset();
  } else {
    alert("please fill the required fields")
  }
};

标签: javascriptfacebookreactjsreact-nativemobile-application

解决方案


那是因为你没有将它分配给任何东西,你的第一个参数应该是空的{}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

 allMap[hash] = Object.assign({}, this.state);

或者你可以这样做:

 allMap[hash] = {...this.state}

推荐阅读