首页 > 解决方案 > 为什么 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;
}

}

标签: reactjsreact-reduxreact-hooksuse-effect

解决方案


好吧,我通过调度'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)])

推荐阅读