[英]can't insert array to a state in react
So i'm getting some weather data from an API through an async function.所以我通过异步 function 从 API 获取一些天气数据。 This function returns an array of objects that i want to set on a state, and when the state receives this array, i want to render the data.
这个 function 返回一个我想在 state 上设置的对象数组,当 state 收到这个数组时,我想渲染数据。
export class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = { 'graficoEnergia': DIA,
weather: []
};
}
componentDidMount() {
async function setWeather(getWeatherFunction, address, component){
const weatherArray = await getWeatherFunction(address)
component.setState({
weather: [...component.state.weather, weatherArray]
})
}
if(!this.props.loading){
setWeather(this.props.weather, this.props.doc.address, this);
}
render() {
return etc
}
}
...
The function is in this.props.weather. function 在 this.props.weather 中。 i have also tried setting the state like this
我也试过像这样设置 state
weather: weatherArray
and和
weather: component.state.weather.concat(weatherArray)
None of this sets the value to the state.这些都没有将值设置为 state。 What am I doing wrong?
我究竟做错了什么?
you should use this.setState
to update state value您应该使用
this.setState
更新 state 值
setWeather = async (getWeatherFunction, address) =>{
const weatherArray = await getWeatherFunction(address)
this.setState({
weather: [...this.state.weather, weatherArray]
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.