【问题标题】:Initialise helper class in a react functional component在反应功能组件中初始化帮助程序类
【发布时间】:2021-08-25 12:03:49
【问题描述】:

从功能组件作为参数传递的类方法被保存在“内存中”并且不反映更新的状态。我可以在状态更改时重新初始化,但希望避免它。

const MyFunctional = (props) => {
    const [state,setState] = useState(0);

    const helper = useRef();

    useEffect(()=>{
        helper.current = new HelperClass(onSuccess,onFailure);
    },[])
    
    /* wish to avoid */

     useEffect(()=>{
        helper.current = new HelperClass(onSuccess,onFailure);
    },[state])



    const onSuccess = (result) =>{
       
       /* Here state == 0 */

    }

    const onFailure = (error) =>{
       /* Here state == 0 */

    }
}

【问题讨论】:

    标签: javascript react-native react-functional-component


    【解决方案1】:

    您需要一个额外的 ref 才能在异步回调中使用最新值。

    要么

    const MyFunctional = (props) => {
      const [state, setState] = useState(0);
      const latestStateRef = useLatest(state);
      const helper = useRef();
      useEffect(() => {
        helper.current = new HelperClass(onSuccess, onFailure);
      }, []);
    
      const onSuccess = (result) => {
        console.log(latestStateRef.current);
      };
    
      const onFailure = (error) => {
        console.log(latestStateRef.current);
      };
    };
    

    【讨论】:

      猜你喜欢
      • 2017-07-16
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多