[英]React Component not rendering a passed props
I'm trying to pass an array of users as a props to a component, when I change something and click save, the array is showed in the component but when I hit refresh, the array is disappeared, here is my code:我正在尝试将一组用户作为道具传递给组件,当我更改某些内容并单击保存时,该数组显示在组件中,但是当我点击刷新时,该数组消失了,这是我的代码:
First in my App.js
I'm reading an array of users from the database (works perfectly shows the list of users):首先在我的
App.js
中,我从数据库中读取一组用户(完美显示用户列表):
const [users,setUsers] = React.useState([]);
React.useEffect( () => {
async function fetchData() {
await axios.get('/api/users/')
.then(response => {
setUsers(response.data);
});
}
fetchData();
}
, []);
Then, also in App.js
, I'm rendering a ListComponent
that takes the users array and shows the users:然后,同样在
App.js
中,我正在渲染一个ListComponent
,它采用 users 数组并显示用户:
return (
<ListComponent users={users} />
);
}
In my ListComponent
after a page refresh the console.log
shows an empty array []
在我的
ListComponent
页面刷新后, console.log
显示一个空数组[]
const ListComponent = (props) => {
React.useEffect(()=>{
console.log(props.users); // []
},[])
When you refresh the page, the ListComponent
will be remounted, and what you are logging, is the state of the component just after it is mounted, so the user array is not already fetched.当您刷新页面时,
ListComponent
将被重新挂载,而您正在记录的是该组件刚刚挂载后的 state,因此尚未获取用户数组。 If you want log it when it is fetched, you should add the user array in the dependency array of the useEffect
function:如果要在获取时记录它,则应将用户数组添加到
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]);
// ...
};
If you still cannot see the user array, it means that something is not happening as expected in your fetchData
function I guess.如果您仍然看不到用户数组,这意味着我猜在您的
fetchData
function 中没有像预期的那样发生某些事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.