如何在setState

时间:2019-04-21 04:21:29

标签: reactjs

我有一个状态为nextDayWeather的数组,我想为setState内的那个数组元素设置值。如下面的代码中所述,我需要将其传递给组件调用WeekTempretureControl。请指导我。谢谢。

const API_KEY = "422edb157a5c2e7a35763933c19def46";

class App extends Component {
  state = {
    nextDayWeather: [
      {
        id: 1,
        nextDayDate: new Date(),
        nextDayTempreture: 23.4,
        nextDayWeatherLabel: "rain"
      },
      {
        id: 2,
        nextDayDate: new Date(),
        nextDayTempreture: 28.4,
        nextDayWeatherLabel: "clear sky"
      },
      {
        id: 3,
        nextDayDate: new Date(),
        nextDayTempreture: 25.4,
        nextDayWeatherLabel: "broken clouds"
      }
    ]
  };

  getWeather = async e => {
    e.preventDefault();
    const city = e.target.elements.city.value;
    const api_call = await fetch(
      `http://api.openweathermap.org/data/2.5/forecast?q=${city}&APPID=${API_KEY}&units=metric`
    );
    const data = await api_call.json();
    console.log(data);

    this.setState({
      //nextDayDate: new Date(),
      //nextDayTempreture: data.list[0].main.temp,
      //nextDayWeatherLabel: data.list[0].weather[0].description,
    });
  };

  render() {
    // let {currentLocation, currentDate, currentTempreture, currentWeatherLabel, currentWind, currentHumidity, currentPressure } = this.state.currentWeather;
    let { nextDayWeather } = this.state;

    return (
      <div id="bsec" className="b-color body-sec">
        <div className="main-wrapper">
          <WeekTempretureControl nextDayWeather={nextDayWeather} />
        </div>
      </div>
    );
  }
}

export default App;

2 个答案:

答案 0 :(得分:0)

 setState({...state, nextDayWeather: state.nextDayWeather.map( (day,index) => {
  if (index === THE_INDEX_YOU_ARE_LOOKING_TO_CHANGE) {
    return {
      id: index,
      nextDayDate: new Date(),
      nextDayTempreture: 5,
      nextDayWeatherLabel: "Rain"
    }
  }
  return {...day}

})})

首先传播您的状态,以便您所做的任何更改都将保留下来。

您获取第二天的数组并对其进行映射,如果每个对象与索引都不匹配,则将其散布,然后在所需的索引上将其更改为所需的任何内容。

答案 1 :(得分:0)

由于状态应该一成不变地更新,所以 首先使用lodash中的clonedeep()或使用散布运算符复制状态,

然后更新克隆的对象,

然后使用更新的数据设置状态

getWeather = async e => {
e.preventDefault();
const city = e.target.elements.city.value;
const api_call = await fetch(
  `http://api.openweathermap.org/data/2.5/forecast?q=${city}&APPID=${API_KEY}&units=metric`
);
const data = await api_call.json();
console.log(data);
let updatedArray = clonedeep(this.state.nextDayWeather);
 updatedArray.forEach(item => {
   item.nextDayDate = new Date()
   item.nextDayTemp = data.list[0].main.temp
   item.nextDayWeatherLabel = data.list[0].weather[0].description
  })
 // so the piont is we use forEach/map/find/filter methods of array to update 
  all or some 
  // and if you want to update any one item inside the above array then any 
one of filter/map/... etc
  updatedArray.forEach(item => {
    if(item.id === 1){
      item.nextDayDate = new Date()
     item.nextDayTemp = data.list[0].main.temp
     item.nextDayWeatherLabel = data.list[0].weather[0].description
   }
  })
  // the above forEach loop will update only the item with id === 1, rest of 
  the 
  items will remain same

  this.setState({
    nextDayWeather:updatedArray
  });
};