我对一个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>
}
您的函数是异步的,可以使用async
/ await
save: async () => {
const response = await apiFetch( { path:'/url', } );
const newValue = response[0].value;
console.log(newValue);
return <p>{newValue}</p>
}
看来您需要退还诺言。现在,您向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>
});
}