[英]Strange behavior of useState() method of react hook while fetching data from axios
我正在使用 axios 庫通過 json-server 從 json 文件中獲取數據。 當我在單個組件中加載和使用響應 object 時,它運行良好。 但是,當我將此響應 object 從父組件傳遞給子組件時,它不會加載數據。 也沒有收到任何錯誤,有人可以幫我理解差異以及我的方法有什么問題嗎?
//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;
我的猜測是useState
是異步的,與 Class 組件中的setState
相同。 由於其異步性質,您無法記錄任何內容 - 在 useState 實際執行任何操作之前執行日志。
如果你真的想這樣做,你可以將 useState 的值初始化為一個空數組並設置一個 useEffect 鈎子,在你的依賴數組中使用props.notex
,如下所示:
useEffect(() => {
if (props.notex) setNotes(props.notex)
}, [props.notex])
然后在返回
return (
<div>
<ul>
{notes.length && generateRows()}
</ul>
</div>
)
但是您可以將道具從父級傳遞給子級,而無需在子組件中設置 state。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.