首页 > 解决方案 > 如何在状态更改后停止 useEffect 运行?

问题描述

这里的问题是,当用户注销时,isAuthed变成null(如预期的那样)并且触发useEffect(),然后isAuthed变成false. 正因为如此,当用户登录时,登录是成功的,但是isAuthed已经成功了,false所以不会调用私有路由。我该如何解决这个问题?

状态由 Redux 处理。isAuthed的初始值为null

提前谢谢你的帮助。

function App() {

  return (
    <Provider store={store}>
        <BrowserRouter>
              <Switch>
                <Route exact path="/" component={Home} />
                <PublicRoute path="/login" component={Login} />
                <PrivateRoute path="/dashboard" component={Dashboard} />

function PrivateRoute({ component: Component, isAuthed, ...rest }) {
  
  async function verifyUser() {
    const res = await fetch(,);    // call users/me endpoint
    if (res.status === 200) {
      // dispatch action to change `isAuthed` to `true`

    } else {
      // dispatch action to change `isAuthed` to `false`
    };
  };

  useEffect(() => {
    if (isAuthed === null) {
      verifyUser();
    }
  }, [isAuthed]);


  return (
    <Route
      {...rest}
      render={(props) => isAuthed == null ? "loading" :
        isAuthed == true ? <Component {...props} /> : <Redirect to={{ pathname: '/', state: { from: props.location } }} />}
    />
  );
};




function PublicRoute({ component: Component, isAuthed, ...rest }) {
    return (
        <Route
            {...rest}
            render={(props) => isAuthed == false || isAuthed == null ? <Component {...props} /> : <Redirect to={{ pathname: '/' }} />}
        />
    )
};


 const handleLogin = async (event) => {
        event.preventDefault();

        const res = await fetch(,);    // call login endpoint to check user credentials
        if (res.status === 200) {
            props.history.push('/dashboard');
         
        } else {}
         

标签: javascriptreactjsreduxuse-effect

解决方案


推荐阅读