[英]React Component not rendering a passed props
我正在嘗試將一組用戶作為道具傳遞給組件,當我更改某些內容並單擊保存時,該數組顯示在組件中,但是當我點擊刷新時,該數組消失了,這是我的代碼:
首先在我的App.js
中,我從數據庫中讀取一組用戶(完美顯示用戶列表):
const [users,setUsers] = React.useState([]);
React.useEffect( () => {
async function fetchData() {
await axios.get('/api/users/')
.then(response => {
setUsers(response.data);
});
}
fetchData();
}
, []);
然后,同樣在App.js
中,我正在渲染一個ListComponent
,它采用 users 數組並顯示用戶:
return (
<ListComponent users={users} />
);
}
在我的ListComponent
頁面刷新后, console.log
顯示一個空數組[]
const ListComponent = (props) => {
React.useEffect(()=>{
console.log(props.users); // []
},[])
當您刷新頁面時, ListComponent
將被重新掛載,而您正在記錄的是該組件剛剛掛載后的 state,因此尚未獲取用戶數組。 如果要在獲取時記錄它,則應將用戶數組添加到useEffect
function 的依賴數組中:
const ListComponent = (props) => {
React.useEffect(()=>{
console.log(props.users); // Should be an empty array first, then updated if your fetch function is working properly
},[props.users]);
// ...
};
如果您仍然看不到用戶數組,這意味着我猜在您的fetchData
function 中沒有像預期的那樣發生某些事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.