首页 > 解决方案 > React - 复制状态不返回新对象

问题描述

我试图在 React 的组件函数中复制我的状态,以便我可以更改对象以发出 Ajax 请求。

这是我的代码:

fetchNewThumbnails = () => {

    const { publicationsFilter, currentQuery } = this.state;

    const params = Object.assign({}, currentQuery);

    console.log(params)
    console.log(currentQuery)

    if (publicationsFilter !== 'All') {
      params.test = 'test';
    }

    // some Ajax request here

}

问题是当我params在 if 语句中编辑复制的对象时。publicationsFilter当我复制它并使用我的设置第二次运行该函数时,我'All'希望复制的params对象只是状态的副本,没有test对象中的键,但它仍然存在于函数上次运行时。

记录currentQuery对象总是返回没有params.test密钥的状态,所以我认为它只会复制currentQuery对象,而不是保留前一个params对象。

不完全确定我哪里出错了,如果有任何不清楚的地方,请告诉我!

编辑

currentQuery 对象如下所示:

filter: {
    content_type: "thumbnail",
    fields.thumbnailType.fields.type[match]: "News & Press",
    fields.thumbnailType.sys.contentType.sys.id: "thumbnailType"
}

标签: javascriptreactjsecmascript-6

解决方案


推荐阅读