状态更改时如何更新道具

时间:2020-07-12 11:55:47

标签: reactjs

我的天气应用程序的父组件中有一个方法可以更新单位(公制/英制)。

changeUnit = async (unit) => {
    const forecasts = { ...this.state.forecasts };
    forecasts['unit'] = unit = unit === 'Metric' ? 'Metric' : 'Imperial';
    this.setState({ forecasts });        
}

render() {
    return (
        <div className="weather-data">
            <WeatherOverview 
                currentWeather={this.state.currentForecast} 
                changeUnit={this.changeUnit} 
            />
        </div>
    )
}

此信息向下传递到组件上的天气,然后将其向下传递到currentWeatherComponent

return (
            <div className="weather-overview">
                <CurrentWeatherData weather={this.props.currentWeather} status={this.props.currentWeather.isLoaded} changeUnit={this.props.changeUnit}/>
            </div>
        )

在CurrentWeatherComponent中,我有一个名为unit的变量,该变量通过状态从道具中获取单位。

class CurrentWeatherData extends React.Component {
    
    render() {
        const unit = this.props.weather.unit;
        {console.log(unit)}
    }
   }

状态更新时,单位变量不更新。如何更改单位变量?

0 个答案:

没有答案