我试图在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
是否未定义,因此在某些时候您的代码会尝试读取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>
);
}