亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在渲染組件之前運行 useEffect hook

在渲染組件之前運行 useEffect hook

繁星coding 2023-03-18 14:59:35
我有一個在我的 App.js 文件中使用的 useEffect 掛鉤。它將數據放入我需要在我的應用程序中使用的 redux 存儲中。但它在 useEffect 運行之前呈現,因此數據未定義。然后 useEffect 正確運行。我需要在渲染任何內容之前運行 useEffect。我怎么能那樣做?或者我應該使用什么其他解決方案?我曾嘗試完全刪除 useEffect 并只運行該操作,但這會導致它無休止地運行。這是我的代碼:function App() {  const app = useSelector(state => state.app);  const auth = useSelector(state => state.auth);  const dispatch = useDispatch();  useEffect(() => {    dispatch(authActions.checkUser());  }, [dispatch]);  console.log(auth.user); //undefined  return (    <ThemeProvider theme={!app.theme ? darkTheme : theme}>      <CssBaseline />      <React.Fragment>        {/* TODO: Display drawer only when logged in */}        {/* <Drawer></Drawer> */}        <Switch>          <Route exact path="/" component={Login} />          <Route exact path="/dashboard">            <Dashboard user={auth.user} /> //auth.user is undefined when this gets rendered          </Route>          <Route exact path="/register" component={Register} />        </Switch>      </React.Fragment>    </ThemeProvider>  );}export const checkUser = () => async dispatch => {  let token = localStorage.getItem("auth-token");  if (token === null) {    localStorage.setItem("auth-token", "");    token = "";  }  const tokenRes = await Axios.post("http://localhost:5000/users/tokenIsValid", null, {    headers: { "x-auth-token": token }  });  if (tokenRes.data) {    const userRes = await Axios.get("http://localhost:5000/users/", {      headers: { "x-auth-token": token }    });    dispatch({      type: CHECK_USER,      token,      user: userRes.data    });  }};
查看完整描述

2 回答

?
慕運維8079593

TA貢獻1876條經驗 獲得超5個贊

我需要在渲染任何內容之前運行 useEffect。我怎么能那樣做?

您不能在初始渲染之前useEffect運行。

就像componentDidMount類組件在初始渲染之后運行,在初始渲染之后useEffect運行,然后它的執行取決于你是否傳遞第二個參數,即依賴數組來掛鉤。useEffect

我應該使用什么其他解決方案?

您可以通過確保在異步獲取的數據可用后才呈現它來有條件地呈現內容。

return?(
???{?auth???<render?content>?:?null}
);

或者

return?(
???{?auth?&&?<render?content>?}
);

PS:< or >語法中不包含尖括號。它們只是作為您需要呈現的內容的占位符。


查看完整回答
反對 回復 2023-03-18
?
慕姐4208626

TA貢獻1852條經驗 獲得超7個贊

選擇

您可以使用useMemo, 它不會等待re-render。它也將基于 useEffect 等依賴項以相同的方式執行。

useMemo(()=>{
    doSomething() //Doesn't want until render is completed
     }, [dep1, dep2])


查看完整回答
反對 回復 2023-03-18
  • 2 回答
  • 0 關注
  • 200 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號