代码之家  ›  专栏  ›  技术社区  ›  user944513

使用钩子在react中没有得到更新的状态值?

  •  1
  • user944513  · 技术社区  · 6 年前

    我正在使用 functional components 我有 2 submit updated value .

    https://codesandbox.io/s/peaceful-microservice-ywdoe?file=/src/App.js

    复制步骤

    1. 运行申请者默认单选按钮值为 no
    2. 将任何单选按钮更改为 yes 但它显示了初始状态的原因

     const buttonHandler = useCallback(async e => {
        e.preventDefault();
        console.log(state);
      }, []);
    

    如果改变 blank array to one item in array state like this 。它正常工作,但当我更改 state . ??? 要阻止重新渲染并获取更新状态?

     const buttonHandler = useCallback(async e => {
        e.preventDefault();
        console.log(state);
      }, [state]);
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Drew Reese    6 年前

    state buttonHandler useCallback依赖项数组。

    const buttonHandler = useCallback(async e => {
      e.preventDefault();
      console.log(state);
    }, [state]);
    

    Edit nifty-tree-5yrxq

    或者,不要记住

    const buttonHandler = e => {
      e.preventDefault();
      console.log(state);
    };