简体   繁体   English

反应状态不要重新渲染

[英]React state don't re-render

I am calling api and getting response then setting response data to state. 我正在调用api并获取响应,然后将响应数据设置为state。 Problem is state is still undefined after setState and does not update Weather component with api data 问题是setState之后状态仍未定义,并且不使用api数据更新Weather组件

class App extends React.Component {
  state = {
    temperature: undefined,
    icon: undefined,
    time: undefined,
    timezone: undefined,
    description: "123"
  };

  getWeather = async e => {
    e.preventDefault();
    const location = e.target.elements.city.value;
    const api_call = await fetch(`${GEO_API_URL}${location}`);
    const lngLat = await api_call.json();
    console.log(lngLat);

    const api_call2 = await fetch(
      `${API_URL}${lngLat.latitude},${lngLat.longitude}/?lang=sl&units=si`
    );
    const forecast = await api_call2.json();
    console.log(forecast);

    this.setState = {
      temperature: forecast.currently.temperature,
      icon: forecast.currently.icon,
      time: forecast.currently.time,
      timezone: forecast.timezone,
      description: forecast.currently.summary
    };
    console.log(this.state.temperature);
  };

  render() {
    return (
      <div>
        <Form getWeather={this.getWeather} />

        <Weather
          temperature={this.state.temperature}
          icon={this.state.icon}
          time={this.state.time}
          timezone={this.state.timezone}
          description={this.state.description}
        />
      </div>
    );
  }
}
export default App;

Try using 尝试使用

 this.setState({
      temperature: forecast.currently.temperature,
      icon: forecast.currently.icon,
      time: forecast.currently.time,
      timezone: forecast.timezone,
      description: forecast.currently.summary,
});

instead of 代替

  this.setState = ({
      temperature: forecast.currently.temperature,
      icon: forecast.currently.icon,
      time: forecast.currently.time,
      timezone: forecast.timezone,
      description: forecast.currently.summary,
});

Using the right format for the setState method. 为setState方法使用正确的格式。

this.setState({field: 'new value'});

Now Change the code setState like. 现在更改代码setState之类的。

 this.setState({
      temperature: forecast.currently.temperature,
      icon: forecast.currently.icon,
      time: forecast.currently.time,
      timezone: forecast.timezone,
      description: forecast.currently.summary,
});

另外,对于以前的评论,我建议您从官方文档https://reactjs.org/docs/react-component.html#setstate刷新setState的理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM