简体   繁体   English

如何调用取决于更新的 state 的回调?

[英]How can I call a callback that depends on an updated state in react?

function useRequest() {

  const [accessToken, setAccessToken] = useState(42);
  const [refreshToken, setRefreshToken] = useState(7);
  
  const request = async (url) => {
    try {
      const res = await axios.get(url, { Headers: { Auth: accessToken } });
    } catch (error) {
      if (error.response.status === 401) {
        refresh(() => request(url));
      }
    }
  }
  
  const refresh = async (callback) => {
    const res = await axios.get("myserver.com", { params: { refreshToken }});
    setAccessToken(res.data.accessToken);
    callback()
  }
  
  return request;

}

So I want to call this api and refresh the access token if it expires.所以我想调用这个 api 并在它过期时刷新访问令牌。 Problem is, when I set the access token state in the refresh function, the callback is called with the old state because setState is async.问题是,当我在刷新 function 中设置访问令牌 state 时,使用旧的 state 调用回调,因为 setState 是异步的。 In other contexts, I could just use useEffect but i'm not sure what to do in this case.在其他情况下,我可以只使用 useEffect 但我不确定在这种情况下该怎么做。

If you don't want to use useEffect for whatever reason, another option would be to pass the state you set to the request function, so that it doesn't depend on external variables.如果您出于某种原因不想使用useEffect ,另一种选择是将您设置的 state 传递给request function,以便它不依赖于外部变量。

const request = async (url, accessToken = 42) => {
    try {
        const res = await axios.get(url, { Headers: { Auth: accessToken } });
    } catch (error) {
        if (error.response.status === 401) {
            refresh((accessToken) => request(url, accessToken));
        }
    }
}

const refresh = async (callback) => {
    const res = await axios.get("myserver.com");
    const { accessToken } = res.data;
    setAccessToken(accessToken);
    callback(accessToken);
}

I think you want to store accessToken in a ref instead of in state .我认为您想将accessToken存储在ref中而不是state中。

Official react documentation: https://reactjs.org/docs/hooks-reference.html#useref官方反应文档: https://reactjs.org/docs/hooks-reference.html#useref

useState is async because React assumes state is related to the UI, so state updates are coupled to the React render lifecycle. useState是异步的,因为 React 假设 state 与 UI 相关,因此 state 更新与 React 渲染生命周期相耦合。

Updating the ref is synchronous, and is a good option for persisting data that doesn't need to trigger UI updates.更新ref是同步的,对于不需要触发 UI 更新的持久化数据来说是一个不错的选择。

Your code, but using useRef您的代码,但使用useRef

function useRequest() {

  const accessTokenRef = useRef(42);
  const [refreshToken, setRefreshToken] = useState(7);
  
  const request = async (url) => {
    try {
      const res = await axios.get(url, { Headers: { Auth: accessTokenRef.current } });
    } catch (error) {
      if (error.response.status === 401) {
        refresh(() => request(url));
      }
    }
  }
  
  const refresh = async (callback) => {
    const res = await axios.get("myserver.com", { params: { refreshToken }});
    accessTokenRef.current = res.data.accessToken;
    callback()
  }
  
  return request;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React - 无法更新依赖于另一个 state 的 state 的值 - React - the value of state which depends on another state cannot be updated 如何重构 React 钩子以便我可以在回调中调用它? - How to refactor a React hook so that I can call it inside a callback? 即使我不调用 setstate React,也会更新 state - A state being updated even if I don't call setstate React 如何使用更新的 state 每 x 秒调用一次 function(反应) - How to call a function every x seconds with updated state (React) 我怎么能叫反应状态不同的js - how can i call react state different js 如何使用多个值更新反应状态以及如何通过回调函数依赖该更新状态。 能行吗 - How to update a react state with multiple values and relying on that updated state with a callback function. Will it work? 如何使用 redux 获取更新的状态 - How can I get the updated state with redux 如何在Meteor.call回调中更改React组件状态? - How to change React component state in Meteor.call callback? 反应:我无法在 onScroll 函数中获取更新的状态值 - React: I can't get updated state values in the onScroll function 为什么在我使用 React Hooks 调用 setState 之前,我的 state 会更新,我该如何修复禁用的鼠标指针? - Why is my state beeing updated before i call setState with React Hooks and how do i fix the disabled mouse pointer?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM