【问题标题】:How to create new state for every value in state array如何为状态数组中的每个值创建新状态
【发布时间】:2021-09-13 00:30:52
【问题描述】:

我的状态是这样的

const [state, setState] = useState({
    bpm: [],
    price: null,
    genreTypeId: [],
    filters: [{}],
  });

我想在过滤器中为 bpm 或genreTypeId 中的每个值创建一个对象。这可能吗?

所以这就是我希望我的状态在插入值后的样子。

const [state, setState] = useState({
    bpm: [126,78],
    price: null,
    genreTypeId: [1],
    filters: [{bpm: 126, price: null, genreTypeId: 1},
             {bpm: 76, price: null, genreTypeId: 1}],
  });

【问题讨论】:

  • 这听起来像是那种尝试看看它是否有效,而不是询问人们是否有效的事情。
  • bpmgenreTypeId是什么关系?如果前者有一个元素,后者有多个元素会怎样?
  • 看起来你的状态图过于复杂了。考虑做类似const [bpm, setBpm] = useState([]); const [price, setPrice] = useState(null); ...etc.的事情。
  • @223seneca 两者没有关系。它们只是保存我可以参考新过滤器状态的值
  • @HereticMonkey 我已经可以将状态设置为 bpm、价格和流派类型 ID。状态只是我的占位符,用于保存我可以在过滤器中形成对象数组的值

标签: arrays reactjs state


【解决方案1】:

如果我正确理解您想要循环遍历 bpmgenreTypeId,请尝试以下操作(在我的示例中拉出真实状态而不是硬编码的 state 对象):

const state = {
    bpm: [126, 78],
    price: null,
    genreTypeId: [1, 2],
    filters: []
  }

const filters = []
const { bpm, genreTypeId } = state

if (bpm.length > 0) {
  bpm.forEach(cadence => {
    genreTypeId.forEach(id => {
      filters.push({bpm: cadence, price: null, genreTypeId: id})
    }
  }
} else {
  genreTypeId.forEach(id => {
    // Please note that the following line is just showing an example of when bpm is an empty array, which technically isn't the case here
    filters.push({bpm: [], price: null, genreTypeId: id})
  }
}

const [state, setState] = useState({
    bpm: [126, 78],
    price: null,
    genreTypeId: [1, 2],
    filters
  })

【讨论】:

  • 这感觉像是在正确的轨道上但是 filters.push 不会发生,除非genreTypeId 和 bpm 有值,有没有办法让它们独立?
  • 更新了我的答案。那怎么办?
  • 我需要 bpm、price 和genretypeid 才能独立推送过滤。对于 forEach,这仍然可能吗?
  • 这不是你问的问题。您可能希望更新您的原始问题。
  • 这对你有用吗?如果是这样,请随时接受答案。
猜你喜欢
  • 2022-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
  • 2021-03-27
  • 2018-12-06
  • 2017-08-17
相关资源
最近更新 更多