开发者问题收集

ReactJS TypeError:无法读取未定义的属性(读取‘main’)

2021-10-19
2721

我尝试使用 React JS 制作天气应用,但运行程序时出现错误“TypeError: 无法读取未定义的属性(读取‘main’)”。以下是部分代码:

 return (
 <div className={(typeof weather.main != "undefined") ? ((weather.main.temp > 16 ) ? 
 'app warm':'app'):'app'}>
   <main>

   <div className="search-box">

     <input type='text' 
      className='search-bar' 
      placeholder='Search ...'
      onChange={e => setQuery(e.target.value)}
      value={query}
      onKeyPress={search}
      />
    </div>
    
    {(typeof weather.main != "undefined") ? (
     <div>
      <div className='location-box'>
      <div className='location'>{weather.name}, {weather.sys.country}</div>
      <div className='date'>
        {dateBuilder(new Date())}
      </div>
      </div>
      <div className='weather-box'>
      <div className='temp'>
      {Math.round(weather.main.temp)}
      </div>
      <div className='weather'>
      {weather.weather[0].main}
      </div>
    
      </div>
     </div>
    ): (' ')}
  </main>
   </div>
  );
  }
1个回答

weather 在某些时候未定义。由于您只检查 weather.main 是否未定义,因此在某些时候您的代码会尝试读取 undefined 的字段 main

一种解决方案可能是条件链接。尝试将

(typeof weather.main != "undefined") ? ...

更改为

weather?.main && (...

完整代码

return (
 <div className={`app ${weather?.main?.temp > 16 ? 'app warm':''}`}>
   <main>

   <div className="search-box">

     <input type='text' 
      className='search-bar' 
      placeholder='Search ...'
      onChange={e => setQuery(e.target.value)}
      value={query}
      onKeyPress={search}
      />
    </div>
    
    {weather?.main && (
     <div>
      <div className='location-box'>
      <div className='location'>{weather.name}, {weather.sys.country}</div>
      <div className='date'>
        {dateBuilder(new Date())}
      </div>
      </div>
      <div className='weather-box'>
      <div className='temp'>
      {Math.round(weather.main.temp)}
      </div>
      <div className='weather'>
      {weather.weather[0].main}
      </div>
    
      </div>
     </div>
    ): (' ')}
  </main>
   </div>
  );
  }
Sinan Yaman
2021-10-19