本文讲解如何在 react 函数组件中将 `apifetch` 等异步请求的结果从 `.then()` 内部“提取”出来,供组件其他部分安全使用——核心是借助 `usestate` 管理响应数据,并理解异步操作不可同步读取的本质。
在 React 中,apiFetch(WordPress REST API 封装函数)返回的是一个 Promise,其结果只能在 .then() 或 async/await 的异步上下文中获取。切勿尝试在 .then() 外直接读取 result 变量,因为此时 Promise 尚未完成,变量仍为初始值(如 null 或 undefined)。
✅ 正确做法:使用 useState 声明状态变量存储响应结果,并在 .then() 中通过 setState 更新它:
import { useState, useEffect } from 'react';
function MyComponent() {
const [dataResult, setDataResult] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [isError, setIsError] = useState(false);
const handleSubmit = () => {
setIsLoading(true);
apiFetch({
url: lmn_admin.ajax_url,
method: "POST",
body: formData,
})
.then((result) => {
setDataResult(result); // ✅ 数据存入状态
setIsLoading(false);
setIsSuccess(true);
})
.catch((error) => {
setIsLoading(false);
setIsError(true);
console.error('API error:', error);
});
};
// ✅ 在 JSX 或逻辑中安全使用 dataResult(需处理 null/undefined)
return (
{isLoading && Loading...
}
{isError
&& Submission failed.
}
{isSuccess && dataResult && (
Response received:
{JSON.stringify(dataResult, null, 2)}
)}
);
}
export default MyComponent;⚠️ 注意事项:
useEffect(() => {
if (dataResult) {
console.log('New data arrived:', dataResult);
// 执行依赖 result 的逻辑
}
}, [dataResult]);总结:异步结果“对外可用”的本质不是“取出变量”,而是“驱动状态更新并响应式渲染”。掌握 useState + .then() 的配合模式,是构建健壮 React 数据流的基础。