[英]Strange behavior of useState() method of react hook while fetching data from axios
I am using axios library to fetch data from a json file through json-server.我正在使用 axios 库通过 json-server 从 json 文件中获取数据。 When I am loading and using the response object in a single component it is working perfectly.当我在单个组件中加载和使用响应 object 时,它运行良好。 But when I am passing this response object to child component from parent component it is not loading the data.但是,当我将此响应 object 从父组件传递给子组件时,它不会加载数据。 Also not receiving any errors, can someone please help me to understand the difference and what is wrong with my approach?也没有收到任何错误,有人可以帮我理解差异以及我的方法有什么问题吗?
//Scenario-1 : working perfectly fine:
import React, { useState, useEffect } from 'react';
import Display from './Display';
import Note from './note'
import axios from 'axios';
const App = () => {
const [notes, setNotes] = useState([])
const hook = () => {
axios.get('http://localhost:3001/notes')
.then(response => {
setNotes(response.data)
})
}
useEffect(hook, [])
return (
<div>
{notes.map(n => <Note key={n.id} note={n} />)}
</div>
)
}
export default App;
//Scenario-2 : Not working as expected, also no errors.
const Display = (props) => {
//Receiving data here, can see the values in console.
console.log('inside display, props.notex: ', props.notex);
const [notes, setNotes] = useState(props.notex);
//Blank object, why useState() method is not setting the value of "notes" from "props.notex".
console.log('inside display, notes: ', notes);
const generateRows = () => {
console.log('generateRows: ', notes)
return (
notes.map(n => <Note key={n.id} note={n} />)
)
}
return (
<div>
<ul>
{generateRows()}
</ul>
</div>
)
}
const App = () => {
const [notes, setNotes] = useState([])
const hook = () => {
axios.get('http://localhost:3001/notes')
.then(response => {
setNotes(response.data)
})
}
useEffect(hook, [])
return (
<div>
<Display notex={notes} />
</div>
)
}
export default App;
My guess is that useState
is asynchronous, same as setState
in Class components.我的猜测是useState
是异步的,与 Class 组件中的setState
相同。 Due to its async nature, you are not able to log anything - the log gets executed before the useState actually does anything.由于其异步性质,您无法记录任何内容 - 在 useState 实际执行任何操作之前执行日志。
If you really want to do it this way, you could initialize the value of the useState as an empty array and set up a useEffect hook, with the props.notex
in your dependency array, something like this:如果你真的想这样做,你可以将 useState 的值初始化为一个空数组并设置一个 useEffect 钩子,在你的依赖数组中使用props.notex
,如下所示:
useEffect(() => {
if (props.notex) setNotes(props.notex)
}, [props.notex])
And then in the return然后在返回
return (
<div>
<ul>
{notes.length && generateRows()}
</ul>
</div>
)
But you could just pass the props down from the parent to child without setting the state in the child component.但是您可以将道具从父级传递给子级,而无需在子组件中设置 state。
Hope this helps!希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.