所以我通过异步函数从API获得一些天气数据。这个函数返回一个我想在状态上设置的对象数组,当状态接收到这个数组时,我想渲染数据。
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
}
}
...
函数在this.props.weather中。我也试过这样设置状态
weather: weatherArray
和
weather: component.state.weather.concat(weatherArray)
这些都不会将值设置为状态。我做错了什么?
你应该使用this.setState
来更新状态值
setWeather = async (getWeatherFunction, address) =>{
const weatherArray = await getWeatherFunction(address)
this.setState({
weather: [...this.state.weather, weatherArray]
})
}