使用效果初始状态加载

发布于 2025-02-03 16:45:27 字数 1047 浏览 3 评论 0原文

有人可以解释为什么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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

新雨望断虹 2025-02-10 16:45:28

效果钩在后运行渲染函数完成。如果要呈现效果的结果,请使用状态。将其设置在效果中以触发重新渲染。

如果您想一次执行一次昂贵的操作,请改用usememo

const foodList = useMemo(correctFunction, []);

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.

const foodList = useMemo(correctFunction, []);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文