Свойства объекта при деструктуризации
Добрый день.
Приложений на React.js, но вопрос касается javascript. При доступе к свойствам объекта temp, feels_like, temp_min, temp_max, pressure, я получаю сообщение об ошибке "TypeError: Cannot destructure property 'temp' of 'previously' as it is undefined." Что я делаю не так, в чем моя ошибка? const App = () => { const [data, setData] = useState({}) useEffect(() => { fetch('http://api.openweathermap.org/data/2.5/forecast?q=London&&appid=47f0bb1e397d9c96b56ba33f697a4ea5') .then(res => res.json()) .then(result => setData(result)) }, []) const obj = Object.values(data) const [ , , ,ret, ]=obj const now = ret?.[0]?.main const{temp, feels_like, temp_min, temp_max, pressure, sea_level, grnd_level, humidity, temp_kf} = now return( <div> </div> ) } |
Объект now связан как-нибудь с тем, что вы получаете из fetch?
Если да, то он будет скорее всего undefined. Так как const obj = Object.values(data) const [ , , ,ret, ]=obj const now = ret?.[0]?.main const{temp, feels_like, temp_min, temp_max, pressure, sea_level, grnd_level, humidity, temp_kf} = now будут выполняться раньше, чем придет ответ от fetch и будут выполнены все then |
djekokma,
может вы хотели так ... const {list} = data; const now = list?.[0]?.main; const{temp, feels_like, temp_min, temp_max, pressure, sea_level, grnd_level, humidity, temp_kf} = now; |
Можно конечно и так, но данная ошибка никуда не девается при добавлении строки 4
|
react загрузка данных
djekokma,
макет здесь может не сработать, но примерно так <!DOCTYPE html> <html> <head> <title></title> </head> <body> <div id="root"></div> <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script> <script type="text/babel"> function Example() { const [data, dataSet] = React.useState(null) React.useEffect(() => { async function fetchMyAPI() { let response = await fetch('https://api.openweathermap.org/data/2.5/forecast?q=London&&appid=47f0bb1e397d9c96b56ba33f697a4ea5') response = await response.json() dataSet(response) } fetchMyAPI() }, []) if (data === null) { return 'Загрузка...'; } const {list} = data; const now = list[0].main; const{temp, feels_like, temp_min, temp_max, pressure, sea_level, grnd_level, humidity, temp_kf} = now; return <div>feels_like : {feels_like}</div> } ReactDOM.render(<Example />, document.getElementById("root")) </script> </body> </html> |
Часовой пояс GMT +3, время: 06:19. |