[来自函数JS的ApiFetch传递变量

问题描述 投票:0回答:1

我对一个Endpoing进行api调用,并在apiFetch内部获得一个值。我想从函数外部显示此值,但不会更新。任何想法为什么这样做?

save: () => {
          var newValue="default";
          apiFetch( { path:'/url', } ).then( res => {
          newValue = (res[0].value);

          // this shows the new value
          console.log(newValue);

      } );
      //this shows "default"
      return <p>{newValue}</p>
    }
reactjs fetch-api wordpress-gutenberg
1个回答
0
投票

您的函数是异步的,可以使用async / await

save: async () => {
  const response = await apiFetch( { path:'/url', } );
  const newValue = response[0].value;
  console.log(newValue);
  return <p>{newValue}</p>
}

0
投票

看来您需要退还诺言。现在,您向api发出异步请求,并且在执行此操作时,您返回的newValue仍然只是'default'。

尝试这样:

save: () => {
  var newValue = "default";
  return apiFetch({ path: '/url', }).then(res => {
    newValue = (res[0].value);

    // this shows the new value
    console.log(newValue);
    return <p>{newValue}</p>
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.