You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React技术问题:null变量setState赋值及初始值不显示修复

Hey there! Let's tackle your two React state questions one by one, with clear fixes and explanations:

1. How to handle null values when setting state

When dealing with variables that might be null (like data from an API that could return missing fields), you have a few reliable options to set fallback values in setState:

  • Use conditional checks to explicitly set a default if the value is null:

    this.setState({
      currentTempreture: data.main.temp !== null ? data.main.temp : 20, // Fallback to 20°C if temp is null
      currentLocation: data.name ?? 'Unknown Location' // Shorter syntax for null/undefined checks
    });
    
  • Leverage optional chaining + nullish coalescing (ES2020+) for safer nested property access:
    This is great if you're accessing nested objects that might be undefined or null:

    this.setState({
      currentTempreture: data?.main?.temp ?? 20,
      currentWeatherLabel: data?.weather?.[0]?.description ?? 'Clear'
    });
    

    The ?. operator stops accessing properties if any step is null/undefined, and ?? returns the fallback only if the left side is null or undefined.

2. Fixing missing static default values in your component

Looking at your code, the root issue is a mismatch in your state structure:

  • Your default state stores all weather properties inside a currentWeather object, but
  • When you update state in getWeather, you're adding those properties directly to the root of state, and
  • Your render method is trying to access root-level properties (like this.state.currentLocation) which don't exist in the default state.

Here are two clean fixes:

First, update your render method to pull values from the currentWeather object:

render() {
  const { currentWeather } = this.state; // Destructure for cleaner code
  return (
    <div id="bsec" className="b-color body-sec">
      <div className="main-wrapper">
        <MainWidget
          location={currentWeather.currentLocation}
          date={currentWeather.currentDate}
          tempreture={currentWeather.currentTempreture}
          label={currentWeather.currentWeatherLabel}
          wind={currentWeather.currentWind}
          humidity={currentWeather.currentHumidity}
          pressure={currentWeather.currentPressure ?? ''} {/* Add fallback for missing pressure */}
        />
      </div>
    </div>
  );
}

Then, update getWeather to update the currentWeather object (use the functional setState to safely merge with existing state):

getWeather = async e => {
  // Assume `data` is your API response
  this.setState(prevState => ({
    currentWeather: {
      ...prevState.currentWeather, // Preserve existing properties like currentDate
      currentTempreture: data.main.temp,
      currentLocation: data.name,
      currentWind: data.wind.speed,
      currentHumidity: data.main.humidity,
      currentWeatherLabel: data.weather[0].description
    }
  }));
};

This way, your default values are always accessible, and you only update the fields you need when fetching new data.

Option 2: Move properties to the root of state

If you prefer a flat state structure, adjust your default state to match how you're updating it:

state = {
  currentLocation: 'Colombo',
  currentDate: new Date(),
  currentTempreture: 28.3,
  currentWeatherLabel: 'rain',
  currentWind: 1.5,
  currentHumidity: 60,
  currentPressure: '' // Add a default for pressure to avoid undefined
};

Your existing getWeather and render code will work as-is with this change, since all properties are now at the root level.

A quick note: You're passing pressure to MainWidget but it's not in your default state—make sure to add a default value for it either way to prevent potential errors!

内容的提问来源于stack exchange,提问作者ray.one

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:30:22