reactjs - 为什么 useEffect 挂钩在页面刷新时不起作用?
问题描述
我正在做一个反应项目。我有自己的 API 来获取信息。我正在使用 useEffect 挂钩从 API 获取配置文件信息。我的问题是,当页面第一次挂载时,我可以毫无问题地获取数据,但是如果我刷新页面,它根本就不起作用。我知道我必须给 useEffect 提供第二个参数。我尝试将配置文件作为第二个参数,甚至调度了 getCurrentProfile 函数,但是当我这样做时,它会不断触发获取请求。如果有人可以帮助我,我会很高兴。谢谢。
这是我的个人资料组件:
export const Profile = () => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(getCurrentProfile());
}, [])
const profileReducer = useSelector((state) => state.profile);
const authReducer = useSelector((state) => state.auth);
const { profile, error, loading } = profileReducer;
const { user } = authReducer;
console.log("loading", loading)
console.log("profile", profile)
return loading && profile === null ? (
<div >
<Spinner />
</div>
) :
这是我的个人资料操作:
export const getCurrentProfile = () => async dispatch => {
try {
const res = await axios.get("/api/profile/me");
console.log(res);
dispatch({
type: "GET_PROFILE",
payload: res.data.data
})
} catch (err) {
dispatch({
type: "PROFILE_ERROR",
payload: { msg: err.response.statusText, status: err.response.status }
})
}
}
这是我的配置文件减速器:
export default (state = initialState, action) => {
const { type, payload } = action;
switch (type) {
case "GET_PROFILE":
return {
...state,
profile: payload,
loading: false
}
case "PROFILE_ERROR":
return {
...state,
error: payload,
profile: null
}
case "CLEAR_PROFILE":
return {
...state,
profile: null,
loading: false
}
default:
return state;
}
}
解决方案
好吧,我通过调度'getCurrentProfile'而不是'getCurrentProfile()'来解决它,结果就像一个函数一样使用它会导致连续触发。
const profileReducer = useSelector((state) => state.profile);
const authReducer = useSelector((state) => state.auth);
const { profile, error, loading } = profileReducer;
const dispatch = useDispatch();
useEffect(() => {
if (!profile) {
console.log("It worked")
dispatch(getCurrentProfile());
}
}, [dispatch(getCurrentProfile)])
推荐阅读
- php - 使用 laravel excel 从服务器读取文件的问题
- java - 在 bitcoind 中创建 JSONRPCCLIENT 对象时出现空指针异常
- mysql - mysql查询如何用替换的字符串检查inarray
- linux - 如何在 redhat 7.6 中安装 oci.h 头文件
- google-analytics - Google Analytics(分析)广告具有可在 BigQuery“原始”数据中使用的原始数据
- javascript - onClick 活动选项卡添加/删除类
- android - 当我们尝试在颤动中使用 twitter 登录时,如何处理您的设备上未安装 twitter 异常
- java - 错误:java.net.UnknownHostException:无法解析主机“api.themoviedb.org
- xamarin - Xamarin Forms:在网格单元格中显示多行文本
- java - HQL查询选择两个日期之间的数据不返回任何记录