javascript 推送到 React 状态数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52206812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:52:05  来源:igfitidea点击:

Pushing To React State Array

javascriptarraysreactjsreact-native

提问by user3637804

How can I write this better , I want to do it with setState instead of this.state.floors.push as I know that is bad practice but I couldnt figure it out. Im using react native.

我怎样才能写得更好,我想用 setState 而不是 this.state.floors.push 来做,因为我知道这是不好的做法,但我无法弄清楚。我正在使用本机反应。

FloorAPI.getFloorsByBuildingID(this.state.buildingID).then((response) => response.d.data.map((value) => {
  console.log(value.floorName)
  this.state.floors.push({value: value.floorName})
}))

回答by imjared

// Create a new array based on current state:
let floors = [...this.state.floors];

// Add item to it
floors.push({ value: floorName });

// Set state
this.setState({ floors });

回答by Hemadri Dasari

For now, the best possible and simplest way is

目前,最好和最简单的方法是

  this.setState(previousState => ({
      floors: [...previousState.floors, {"value": value.floorName}]
  }));

回答by duxfox--

FloorAPI.getFloorsByBuildingID(this.state.buildingID).then((response) => { 
  // get current floors
  const { floors } = this.state;

  // get new floors after api request
  const newfloors = response.d.data.map((value) => ({value: value.floorName}))

  // set the new state by combining both arrays
  this.setState({ floors: [...floors, ...newfloors] });
})

回答by Alauddin Afif Cassandra

const { floors } = this.state;

// Add item to it
floors.push({ value: 5 });

// Set state
this.setState({ floors });

回答by Aditya Kuppili

You can use

您可以使用

this.setState({floors: [{value: value.floorName}]}); 

in order to use set state.

为了使用设置状态。

回答by Bradey Whitlock

You can make a new variable and push to the variable then set the state after the map is complete

您可以创建一个新变量并推送到该变量然后在地图完成后设置状态

var tempArray = []

FloorAPI.getFloorsByBuildingID(this.state.buildingID).then((response) => response.d.data.map((value) => {
  tempArray.push({value: value.floorName})
}))

this.setState({floors: tempArray})

回答by Dan Mehlqvist

You can always use the previous state.

您始终可以使用以前的状态。

setState((prevState)=>({
   floors: prevState.floors.push({...})
});

Thats a nice way to avoid directly changing the state. Another way would be to do the following:

这是避免直接更改状态的好方法。另一种方法是执行以下操作:

var newState=[...this.state.floors];
newState.push({...});

setState(()=>({
  floors: newState
)}