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



我试图在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>
);
}

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

一个解决方案可能是条件链。试着改变

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

相关内容

  • 没有找到相关文章

最新更新