【问题标题】:Unable to add object to an array in my state React.js无法在我的状态 React.js 中将对象添加到数组
【发布时间】:2016-10-21 11:59:37
【问题描述】:

所以在我的状态下,我想跟踪一个包含用于查询的对象的数组。我在 Redux 中使用 React.js 并且有 lodash 包。问题是我似乎无法在我的状态下将对象添加到我的数组中。

我希望有人能告诉我如何正确地做到这一点。

这是我的功能:

setFilterActive(type, min, max) {
const filterObj = {
  type: type,
  min: min,
  max: max
};
let state = this.state;
_.reject(state.queryObject.query.filters, filter => filterObj.isEqual(filter));
_.merge(filterObj,state.queryObject.query.filters);
console.log(filterObj);
this.setState(state);
console.log("Filters Array:" , this.state.queryObject.filters);
}

【问题讨论】:

  • 不是你问题的答案,但如果你在 react 中使用 redux,你不应该使用组件的状态。
  • @OriolBG 我认为这不是真的。状态仍然可以使用,但是您拥有的任何状态都应该本地化。说你不应该使用 state 是不必要的。您仍然可以将它用于输入字段,只是为了命名一件事。
  • 抱歉,结果有误。只是在这种情况下,数组似乎对应用程序非常重要。

标签: reactjs redux lodash


【解决方案1】:

试试这个。

  setFilterActive(type, min, max) {
    const filterObj = {
      type: type,
      min: min,
      max: max
    };
    let queryObject = this.state.queryObject;
    _.reject(queryObject.query.filters, filter => filterObj.isEqual(filter));
    let newQueryObject = _.merge(filterObj,queryObject.query.filters);
    console.log(filterObj);
    this.setState({queryObject:newQueryObject});
    console.log("Filters Array:" , this.state.queryObject.filters);
  }

另外建议您应该使用_.assign 而不是_.merge,因为它会改变对象。

【讨论】:

  • 感谢您的回复,但是我的状态数组没有用查询对象更新:(
  • 最后,我设法将变量存储在状态中,最终可能是我构建中的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-14
  • 1970-01-01
  • 2020-06-05
  • 2019-06-16
  • 2021-05-31
  • 2020-11-21
相关资源
最近更新 更多