【问题标题】:React : waiting for a promise反应:等待一个承诺
【发布时间】:2021-06-11 18:38:46
【问题描述】:

我有一个使用 axios 从我的后端获取信息的函数,如下所示:

const getDoH = async () => {
    const user = JSON.parse(localStorage.getItem("user"));
    let config = {
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + user.accessToken,
      },
      params: {
        username: user.username,
      },
    };

    return await axios.get(API_URL + "get", config);
  };

现在我想在启动时将这些值保存到一个全局变量中,所以我使用了这样的初始状态钩子:

const [initialValues, setInitialValues] = useState(() => {
    const initialSwitchState = getDoH().then(
      (response) => {
       setInitialValues(response.data);
      },
      (error) => {
        console.log(error);
      }
    );
    return initialSwitchState;
  });

之后我得到了一个函数,它从数据库中获取值并将它们映射到我的局部变量上,这个函数看起来像这样:

const setStartValues = () => {
    let newValues = initialSwitchState;
        let valueArray = Object.entries(newValues).map((v, index) => {
          v[1] = initialValues.switchValues[index]
          return v
      });
      newValues = Object.fromEntries(valueArray);
      setValues({...newValues});
  }

我想用一个 final 函数调用这个函数,这个函数是另一个像这样的初始状态钩子:

const [values, setValues] = useState(() => {
    const initialState = setStartValues();}

但是当它到达线路时:

v[1] = initialValues.switchValues[index]

initialValues 仍然是一个承诺。而且我看不到哪里出了问题,因为我使用了异步并等待我的初始 getDoH() 函数。 在尝试使用结果之前,我该如何解决这个问题(等待承诺)? 亲切的问候。

【问题讨论】:

    标签: reactjs promise react-hooks use-state


    【解决方案1】:

    这里有两个问题:

    首先,您需要await getDoH(),因为这是一个异步函数。

    第二,useState()是一个同步函数,所以在设置const [initialValues, setInitialValues] = ...之前需要在useEffect()里面做await getDoH()

    【讨论】:

      【解决方案2】:

      Tbh 我用使用效果做了它,它有自己的一系列问题。发现最好的方法是:

      const [values, setValues] = useState(async () => {
          const initialState = await getDoH().then(
            (response) => {
              let newValues = switchState;
              let valueArray = Object.entries(newValues).map((v, index) => {
                v[1] = response.data.switchValues[index]
                return v
            });
            newValues = Object.fromEntries(valueArray);
            setValues({...newValues});
            },
            (error) => {
              console.log(error);
            }
          );
          return initialState;
        });
      

      【讨论】:

        猜你喜欢
        • 2013-09-16
        • 2022-01-09
        • 2019-04-29
        • 2015-06-26
        • 1970-01-01
        • 1970-01-01
        • 2017-06-24
        • 2020-10-31
        • 2019-12-10
        相关资源
        最近更新 更多