【问题标题】:ReactJS TypeError: Cannot read properties of undefined (reading 'main')ReactJS TypeError:无法读取未定义的属性(读取'main')
【发布时间】:2021-12-06 01:49:36
【问题描述】:

我正在尝试在 React JS 中制作天气应用程序,但是当我运行程序时出现错误“TypeError: Cannot read properties of undefined (reading '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>
  );
  }

【问题讨论】:

  • 你用的是哪个 react js 版本
  • 可以包含整个组件吗?我们需要知道你如何定义和加载你的状态变量。

标签: reactjs react-hooks


【解决方案1】:

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

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

(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>
  );
  }

【讨论】:

    猜你喜欢
    • 2022-07-22
    • 2021-11-17
    • 2021-12-28
    • 2021-11-18
    • 2019-05-07
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    相关资源
    最近更新 更多