React技术问题:null变量setState赋值及初始值不显示修复
Hey there! Let's tackle your two React state questions one by one, with clear fixes and explanations:
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.
Looking at your code, the root issue is a mismatch in your state structure:
- Your default state stores all weather properties inside a
currentWeatherobject, but - When you update state in
getWeather, you're adding those properties directly to the root ofstate, and - Your
rendermethod is trying to access root-level properties (likethis.state.currentLocation) which don't exist in the default state.
Here are two clean fixes:
Option 1: Keep state nested in currentWeather (recommended for organization)
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

