Reactjs 为什么';是否在页面刷新时使用Effect钩子工作?

Reactjs 为什么';是否在页面刷新时使用Effect钩子工作?,reactjs,react-redux,react-hooks,use-effect,Reactjs,React Redux,React Hooks,Use Effect,我正在做一个项目。我有自己的API来获取信息。我正在使用useEffect钩子从API获取概要信息。我的问题是,当页面第一次挂载时,我可以毫无问题地获取数据,但如果我刷新页面,它就根本不起作用。我知道我必须给useEffect第二个参数。我试图将profile作为第二个参数,甚至发送了getCurrentProfile函数,但当我这样做时,它会不断地发出fetch请求。如果有人能帮我,我会很高兴的。谢谢 以下是我的个人资料组件: export const Profile = () => {

我正在做一个项目。我有自己的API来获取信息。我正在使用useEffect钩子从API获取概要信息。我的问题是,当页面第一次挂载时,我可以毫无问题地获取数据,但如果我刷新页面,它就根本不起作用。我知道我必须给useEffect第二个参数。我试图将profile作为第二个参数,甚至发送了getCurrentProfile函数,但当我这样做时,它会不断地发出fetch请求。如果有人能帮我,我会很高兴的。谢谢

以下是我的个人资料组件:

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 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;
}

}

您可能希望尝试在useEffect中添加条件逻辑,以便仅在您还没有配置文件时触发分派

导入“/styles.css”; 从“react redux”导入{useDispatch,useSelector}; 从“react”导入{useffect,useCallback}; 从“/action”导入{getCurrentProfile}; 导出常量配置文件=()=>{ const dispatch=usedpatch(); const profileReducer=useSelector((state)=>state.profile); const authReducer=useSelector((state)=>state.auth); const{profile,error,load}=profileReducer; //请在此处阅读更多信息:https://stackoverflow.com/questions/58624200/react-hook-useeffect-has-a-missing-dependency-dispatch const stableDispatch=useCallback(dispatch,[]); useffect(()=>{ 如果(!配置文件){ stableDispatch(getCurrentProfile()); } },[profile,stableDispatch]); const{user}=authReducer; 控制台日志(“加载”,加载); console.log(“profile”,profile); 返回加载和配置文件===null?微调器:“实际配置文件”; }; 导出默认配置文件; 此外,您目前似乎没有对
加载
状态块做任何事情,至少从您在这里分享的内容来看是这样。您可能希望调度一个操作,指示您在开始提取之前正在加载,然后在收到响应时将其设置为false

请查看此代码沙盒以供参考:

减速器:

const initialState={
配置文件:空,
加载:错误
};
导出常量配置文件=(状态=初始状态,操作)=>{
const{type,payload}=action;
开关(类型){
案例“加载配置文件”:
返回{
……国家,
加载:正确
};
案例“获取个人资料”:
返回{
……国家,
简介:有效载荷,
加载:错误
};
案例“配置文件错误”:
返回{
……国家,
错误:有效载荷,
配置文件:空
};
案例“CLEAR_PROFILE”:
返回{
……国家,
配置文件:空,
加载:错误
};
违约:
返回状态;
}
};
export const auth=(state={},action)=>{
返回状态;
};
操作创建者:

从“axios”导入axios;
导出常量getCurrentProfile=()=>async(分派)=>{
试一试{
分派({type:“加载配置文件”});
const res=等待axios.get(“https://jsonplaceholder.typicode.com/users/1");
控制台日志(res);
派遣({
键入:“获取_配置文件”,
有效载荷:res.data.data
});
}捕捉(错误){
派遣({
类型:“配置文件错误”,
有效负载:{msg:err.response.statusText,状态:err.response.status}
});
}
};
index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore, combineReducers, applyMiddleware } from "redux";
import { profile, auth } from "./reducers";
import App from "./App";
import thunk from "redux-thunk";

const store = createStore(
  combineReducers({
    profile,
    auth
  }),
  applyMiddleware(thunk)
);

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </StrictMode>,
  rootElement
);

从“react”导入{StrictMode};
从“react dom”导入react dom;
从“react redux”导入{Provider};
从“redux”导入{createStore、CombineReducer、applyMiddleware};
从“/reducers”导入{profile,auth}”;
从“/App”导入应用程序;
从“redux thunk”导入thunk;
const store=createStore(
组合传感器({
轮廓
认证
}),
applyMiddleware(thunk)
);
const rootElement=document.getElementById(“根”);
ReactDOM.render(
,
根元素
);

我通过调度“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)])

你能补充一个问题吗?你把什么放进依赖数组(useEffect的第二个参数)中,导致它不断地获取数据?所以我试着给useEffect添加一个条件逻辑。为此,我必须在useffect之前声明profileReducer。我将配置文件放入dependecy数组。它在第一次挂载时仍然有效,但是刷新页面根本不会激发useEffect。嗯,很有趣。你检查过我共享的沙箱了吗?看起来它正在刷新那里。我还添加了一些关于加载到动作创建者和还原器的内容,感谢您的帮助。结果是我犯了一个愚蠢的错误。我公布了我犯的错误,如果你愿意,你可以查出来。对不起,占用了您的时间,再次感谢:)不用担心!谢谢分享修复。我认为在依赖项数组中添加函数有时会出现问题,通常鼓励使用useCallback钩子来创建函数的稳定版本,因此每次都不是新函数。
   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)])