代码结构
import { createEffect, createSignal } from 'solid-js';
// 创建信号存储用户信息和用户ID
const [userInfo, setUserInfo] = createSignal(null);
const [userId, setUserId] = createSignal(null);
createEffect(() => {
// 获取当前用户ID
const currentUserId = userId();
// 如果用户ID存在,则进行API调用
if (currentUserId) {
const controller = new AbortController();
const { signal } = controller;
fetch(`/api/user/${currentUserId}`, { signal })
.then(response => response.json())
.then(data => {
// 只有在当前用户ID未发生变化时才更新用户信息
if (userId() === currentUserId) {
setUserInfo(data);
}
})
.catch(error => {
if (error.name!== 'AbortError') {
console.error('Error fetching user info:', error);
}
});
// 返回清理函数,在组件卸载或依赖变化时取消请求
return () => controller.abort();
}
});
// 模拟更新用户ID的函数
const updateUserId = newId => {
setUserId(newId);
};
解释
- 信号创建:
- 使用
createSignal
创建了userInfo
和userId
两个信号。userInfo
用于存储获取到的用户信息,初始值为null
;userId
用于存储用户ID,初始值也为null
。
createEffect
:
createEffect
会在其依赖的信号(这里是userId
)发生变化时自动运行。
- 首先获取当前的
userId
,如果userId
存在,则发起异步API调用。
- 使用
AbortController
来控制请求,在createEffect
重新运行(例如userId
变化)或组件卸载时,通过调用controller.abort()
取消未完成的请求,避免重复请求。
- 在API调用成功后,检查当前的
userId
是否与发起请求时的userId
一致,只有一致时才更新userInfo
,这样可以避免因userId
在请求过程中变化而导致的数据不一致问题。
- 更新函数:
updateUserId
函数用于模拟更新userId
,当userId
更新时,createEffect
会重新运行,触发新的API调用获取最新的用户信息。