【问题标题】:React change array in state array在状态数组中反应更改数组
【发布时间】:2020-07-21 09:49:53
【问题描述】:

我在克隆数组时遇到问题。

我将电影列表发送到 API,但它没有“密钥”。

所以我想更改“API 的 ID”->“我的状态密钥”

state={
  movies:[]
};

const movieList = axios.get("URL.json"); //It is not having key value

在“this.setState()”处我该怎么做?

抱歉没有经验的解释

【问题讨论】:

  • 为什么在响应没有的情况下需要 key 属性?
  • 您希望新结构是键数组吗:数字?而不是 id: number?
  • 可能性很小,但是如果您想这样做以便拥有映射 JSX 的“键”,则不需要这样做。使用id 作为您的key,因为它们是独一无二的。如果这不是您的意图,请尝试在您的问题中提供更多详细信息。

标签: reactjs react-native


【解决方案1】:

你可以像这样使用reduce:

const movieList = [ {id:1}, {id:2}, {id:3}]
const keyMovieList = movieList.reduce((acc,rec)=>[...acc, {key:rec.id}], [])

在操场上见:https://jscomplete.com/playground/s538985

【讨论】:

  • 我认为这是我见过的最奇怪的reduce用法...如果要更改数组中每个元素的结构,为什么不使用.map? const keyMovieList = movieList.map(input=> { return {key: input.id} })
猜你喜欢
  • 2019-04-29
  • 2021-10-22
  • 2020-03-29
  • 2022-07-08
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
  • 2022-06-27
  • 2019-03-08
相关资源
最近更新 更多