【问题标题】:React | props inside UseCallBack not updating inside custom hook反应 | UseCallBack 内的道具未在自定义挂钩内更新
【发布时间】:2020-03-05 11:35:10
【问题描述】:

我已经构建了一个自定义的自定义帖子挂钩,它返回 API 响应和 API 帖子。我正在使用useCallback 钩子来设置Response state

问题出在哪里Package prop 没有在useCallback 挂钩内更新。

当我在useCallback 钩子之外记录Package 时,我在属性中得到了正确的数据。但是,当我在 useCallback 挂钩中记录 Package prop 时,Package 的值不会改变。

不管我按了多少次

我尝试过创建一个订单state,每次Package prop 更新时都会更新,但是每当我将Package 设置为scope 中的一个值时,我都会得到一个无限循环。

我还把 Package 添加到了 useCallback 钩子的 scope

示例

  React.useEffect(() => {
    setOrder(Package);
  }, [Package]);

我期望发生的是,每当我调用我的自定义 usePostOrder 钩子时,useCallback 内的 Package 的值总是与最新传递的 prop 保持同步.

自定义挂钩

/**
 * custom post hook that returns the API response and the API post function
 * @param {string} url
 * @param {object} Package
 * @returns {array} and @param {function}
 */

export const usePostOrder = (url, Package) => {
  const [loading, setLoading] = React.useState(true);
  const [order, setOrder] = React.useState(Package);
  const [response, setResponse] = React.useState({
    config: {
      data: []
    },
    data: {
      id: 0
    }
  });

  console.log("outside func", Package);
  const postOrder = React.useCallback(async () => {
    console.log("inside func", Package);
  }, [url, loading, Package]);

  return [response, postOrder];
};

Jake Luby 的回答 稍作调整

/**
 * custom post hook that returns the API response and the API post function
 * @param {string} url
 * @param {object} Package
 * @returns {array} and @param {function}
 */

export const usePostOrder = (url, Package, send) => {
  const [postOrder, setPostOrder] = React.useState();
  const [response, setResponse] = React.useState({
    config: {
      data: []
    },
    data: {
      id: 0
    }
  });

  React.useEffect(() => {
    const getData = async send => {
      //this will have the updated input Package
      await axios
        .post(ApiUrl + url, Package)
        .then(function(response) {
          setResponse(response);
        })
        .catch(function(error) {
          setResponse(error);
          console.log(error);
        });
    };

    send && getData();
  }, [send]); //this will run when url or Package changes

  return [response, postOrder];
};

useAsyncEndpoint.PropTypes = {
  url: PropTypes.url,
  user: PropTypes.object,
  club: PropTypes.object,
  cartItems: PropTypes.array
};

我怎么称呼这个钩子

import {usePostOrder} from "./yourHooksFolder"
  const [send, setSend] = React.useState(false);
  const [response, postOrder] = usePostOrder(
    "url",
    createOrder(user, store, cartItems),
    send
  );

  React.useEffect(() => {
    setSend(false);
  }, [response]);

// send order
  const onGoToPaymentPressed = () => {
    setSend(true);
  };



【问题讨论】:

    标签: javascript reactjs react-native react-hooks usecallback


    【解决方案1】:

    useCallback 不应该这样使用。它实际上并不运行该函数,它只是将其记忆,以便在渲染之间不会重新创建相同的函数。

    您想要的是 useEffect 钩子并将 postOrder 作为状态的一部分:

    export const usePostOrder = (url, Package) => {
      const [postOrder, setPostOrder] = React.useState()
      const [response, setResponse] = React.useState({
        config: {
          data: []
        },
        data: {
          id: 0
        }
      })
    
    
      React.useEffect(() => {
        const getData = async url => {
            //this will have the updated input Package
            console.log(Package) 
    
            //here is where you'll have your REST calls
    
            //set your data which will then update the return values in the hook and cause a rerender
            setPostOrder(returnValue)
            setResponse(someResponse)
        }
    
        getData()
      }, [url, Package]) //this will run when url or Package changes
    
      return [response, postOrder]
    }
    

    【讨论】:

    • 感谢您的回复!我还决定传递一个 send prop 这是一个布尔值。如果该值为真,那么它将执行getData() 函数。防止不必要的请求。你会推荐这个吗?
    • 不,我建议使用 useEffect,因为它可以在没有额外听众的情况下完成您想要的开箱即用操作
    猜你喜欢
    • 2020-01-23
    • 1970-01-01
    • 2020-07-20
    • 2020-08-18
    • 2021-11-18
    • 1970-01-01
    • 2019-07-27
    • 2022-12-03
    • 1970-01-01
    相关资源
    最近更新 更多