为了账号安全,请及时绑定邮箱和手机立即绑定

反应状态不重新渲染

反应状态不重新渲染

米脂 2021-09-17 21:00:59
我正在调用 api 并获得响应,然后将响应数据设置为状态。问题是在 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;
查看完整描述

3 回答

?
慕工程0101907

TA贡献1887条经验 获得超5个赞

尝试使用


 this.setState({

      temperature: forecast.currently.temperature,

      icon: forecast.currently.icon,

      time: forecast.currently.time,

      timezone: forecast.timezone,

      description: forecast.currently.summary,

});

代替


  this.setState = ({

      temperature: forecast.currently.temperature,

      icon: forecast.currently.icon,

      time: forecast.currently.time,

      timezone: forecast.timezone,

      description: forecast.currently.summary,

});


查看完整回答
反对 回复 2021-09-17
?
偶然的你

TA贡献1841条经验 获得超3个赞

为 setState 方法使用正确的格式。


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

现在更改代码 setState 之类的。


 this.setState({

      temperature: forecast.currently.temperature,

      icon: forecast.currently.icon,

      time: forecast.currently.time,

      timezone: forecast.timezone,

      description: forecast.currently.summary,

});


查看完整回答
反对 回复 2021-09-17
  • 3 回答
  • 0 关注
  • 163 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信