使用效果初始状态加载
有人可以解释为什么console.log(食品清单)返回空数组而不是过滤的数组? 我正在制作分页逻辑,我需要先滤波数组,然后显示它。但是,这就像副作用,只能完成一次,因为还有其他一些事情会触发组件重新执行,因此必须具有使用效率。 虚拟代码只是该功能上方的数据,您不必打扰它。
功能1
const correctFunction = () => {
const pages = Math.ceil(DUMMY_FOOD.length / 5);
const arr = [];
let helpArr = [];
let c = 0;
for (let i = 0; i < pages; i++) {
for (let j = c; j < c + 5; j++) {
helpArr.push(DUMMY_FOOD[j]);
}
c += 5;
arr.push(helpArr);
helpArr = [];
}
DUMMY_FOOD = arr;
return DUMMY_FOOD;
};
组件
const MenuList = () => {
const navigate = useNavigate();
const location = useLocation();
const params = useParams();
const [page, setPage] = useState(2);
let foodList = [];
console.log(DUMMY_FOOD);
useEffect(() => {
foodList = correctFunction();
}, []);
console.log(foodList);
ect...
Can somebody explain why does console.log(foodList) return empty array instead of filtered array?
I am making pagination logic, and I need to filter array first and then display it. However, this is like side effect and should only be done once because there are some other things which will trigger component re-executing so this has to be in useEffect.
Dummy code is just data above this function and you dont have to bother with it.
Function 1
const correctFunction = () => {
const pages = Math.ceil(DUMMY_FOOD.length / 5);
const arr = [];
let helpArr = [];
let c = 0;
for (let i = 0; i < pages; i++) {
for (let j = c; j < c + 5; j++) {
helpArr.push(DUMMY_FOOD[j]);
}
c += 5;
arr.push(helpArr);
helpArr = [];
}
DUMMY_FOOD = arr;
return DUMMY_FOOD;
};
Component
const MenuList = () => {
const navigate = useNavigate();
const location = useLocation();
const params = useParams();
const [page, setPage] = useState(2);
let foodList = [];
console.log(DUMMY_FOOD);
useEffect(() => {
foodList = correctFunction();
}, []);
console.log(foodList);
ect...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
效果钩在后运行渲染函数完成。如果要呈现效果的结果,请使用状态。将其设置在效果中以触发重新渲染。
如果您想一次执行一次昂贵的操作,请改用
usememo
。Effect hooks are run after the render function is complete. If you want to render the result of an effect, use a state. Set it inside the effect to trigger a re-render.
If you want to do an expensive operation once, then use
useMemo
instead.