在react组件/redux工具包之外的函数中使用Dispatch

问题描述 投票:0回答:2

我需要帮助来解决此错误:

“在既不是 React 函数组件也不是自定义 React Hook 函数的函数中调用了 useDispatch”。

说明:

store.jsuserSlice.js 保存了我的 Redux 相关事物(rtk)的定义。

Auth.js 旨在保存身份验证/注销功能并保持 redux“用户”存储更新。现在我只有谷歌身份验证,当我调用redirectToGoogleSSO时,它会被验证。

身份验证部分工作完美,我正在正确检索用户信息,但我很难使其更新用户存储。 dispatch(fetchAuthUser()) 是我收到错误的地方。

Sidebar.js 是一个导航侧边栏,其中包含用于登录/注销以及访问 profile.js 的菜单(尚未实现)。 如果我将 Auth 中的所有代码放入侧边栏组件中,身份验证工作和 redux 存储都会被填充,但我想将内容保留在 Auth.js 中,这样我就可以在其他组件中使用它,而不仅仅是在侧边栏中.


//store.js:

import { configureStore } from '@reduxjs/toolkit';
import userReducer from './userSlice';

export default configureStore({
    reducer: {
        user: userReducer
    }
});

//userSlice.js

import { createSlice } from '@reduxjs/toolkit';
import axios from "axios";

export const userSlice = createSlice({
  name: 'user',
  initialState: { 
    email: 'teste@123',
    name: 'teste name',
    picture: 'teste pic',
    isAuthenticated: false
  },
  reducers: {
    setUser (state, actions) {
      return {...state,     
          email: actions.payload.email,      
          name: actions.payload.name,
          picture: actions.payload.picture,
          isAuthenticated: true
         }
    },
    removeUser (state) {
      return {...state, email: '', name: '', picture: '', isAuthenticated: false}
    }
  }
});

export function fetchAuthUser() {  

  return async dispatch => {

    const response = await axios.get("/api/auth/user", {withCredentials: true}).catch((err) => {
      console.log("Not properly authenticated");
      dispatch(removeUser());
    });

    if (response && response.data) {
      console.log("User: ", response.data);
      dispatch(setUser(response.data));
    }
  }
};

export const { setUser, removeUser } = userSlice.actions;

export const selectUser = state => state.user;

export default userSlice.reducer;

//Auth.js

import React, {  useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { fetchAuthUser } from '../../redux/userSlice';

export const AuthSuccess = () => {
    useEffect(() => {
        setTimeout(() => {
            window.close();
        },1000);
    });

    return <div>Thanks for loggin in!</div>
}

export const AuthFailure = () => {
    useEffect(() => {
        setTimeout(() => {
            window.close();
        },1000);
    });

    return <div>Failed to log in. Try again later.</div>
}

export const redirectToGoogleSSO = async() => { 
    const dispatch = useDispatch(); 
    let timer = null;
    const googleAuthURL = "http://localhost:5000/api/auth/google";
    const newWindow = window.open(
        googleAuthURL,
        "_blank",
        "toolbar=yes,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=600"
    );

    if (newWindow) {
        timer = setInterval(() => {
            if(newWindow.closed) {
                console.log("You're authenticated"); 
                dispatch(fetchAuthUser()); //<----- ERROR HERE ---->
                if (timer) clearInterval(timer);
            }
        }, 500);
    }
}

//侧边栏.js

import React from 'react';
import { Link } from 'react-router-dom';
import { redirectToGoogleSSO } from '../auth/Auth';
import { useSelector } from 'react-redux';

export const Sidebar = () => { 

    const handleSignIn = async() => { 
        redirectToGoogleSSO();
    };

    const {name,picture, isAuthenticated} = useSelector(state => state.user);  

    return (  
        <div id="sidenav" className="sidenav">
            <div className="nav-menu">
                <ul> 
                    {
                        isAuthenticated  
                        ? <li>
                            <img className="avatar" alt="" src={picture} height="40" width="40"></img>                        
                            <Link to="/" className="user">{name}</Link> 
                            <ul>
                                <li><Link to="/"><i className="pw-icon-export"/> logout</Link></li>
                            </ul>
                        </li>

                        : <li>
                            <Link to="/" className="login" onClick={handleSignIn}>                         
                                <i className="pw-icon-gplus"/>&nbsp;&nbsp;
                                Sign In / Sign Up 
                            </Link> 
                        </li> 
                    } 
                </ul>
            </div>
        </div> 
      )
}
reactjs react-redux
2个回答
5
投票

您只能从 React 组件或自定义钩子中使用 useDispatch 钩子,在您的情况下,您应该使用

store.dispatch()
,尝试执行以下操作:

import { configureStore } from '@reduxjs/toolkit';
import userReducer from './userSlice';

// following the docs, they assign configureStore to a const
const store = configureStore({
    reducer: {
        user: userReducer
    }
});
export default store;

编辑:我还注意到你正在尝试分派一个不是动作的函数,redux不能像那样工作,你应该只分派你在reducer中定义的动作,否则你的状态将不一致.

首先,将

fetchAuthUser
移动到另一个文件,例如 apiCalls.ts 或其他任何文件,这只是为了避免从
store.js
循环导入。

此后,请致电 store.dispatch

fetchAuthUser
:

// File with the fetch function
// Don't forget to change the path
import store from 'path/to/store.js'
export function fetchAuthUser() {

    const response = await axios.get("/api/auth/user", {withCredentials: true}).catch((err) => {
      console.log("Not properly authenticated");
      store.dispatch(removeUser());
    });

    if (response && response.data) {
      console.log("User: ", response.data);
      store.dispatch(setUser(response.data));
    }

};

在 Auth.js 中,您不必调用调度,因为您已经在函数中调用了它。

export const redirectToGoogleSSO = async() => { 
    let timer = null;
    const googleAuthURL = "http://localhost:5000/api/auth/google";
    const newWindow = window.open(
        googleAuthURL,
        "_blank",
        "toolbar=yes,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=600"
    );

    if (newWindow) {
        timer = setInterval(() => {
            if(newWindow.closed) {
                console.log("You're authenticated");

                // Just call the fetchAuthUser, you are already dispatching the state inside this function
                await fetchAuthUser();
                if (timer) clearInterval(timer);
            }
        }, 500);
    }
}

因此请记住,无论您需要在 React 组件或自定义钩子之外使用分派,您必须使用 store.dispatch,否则它将无法工作,并且不要忘记仅分派操作来保持状态持续的。我建议您阅读有关 redux 的核心概念,并观看此视频以更好地了解它的底层工作原理。希望我能帮上一点忙!


0
投票

正如错误所述,您正在

useDispatch
中调用
Auth.js-> redirectToGoogleSSO
。这既不是 React Component,也不是 React Hook 函数。您需要在其中任何一个中调用
useDispatch
。所以你可以:

  1. 通过在

    useDispatch
    本身中调用
    redirectToGoogleSSO
    handleSignIn
    来处理组件中用户信息的 redux 部分和 Google SSO 部分(这现在可能更容易实现,您只需移动调度代码从
    redirectToGoogleSSO
    handleSignIn
    ),或

  2. redirectToGoogleSSO
    变成一个可以从组件内部调用的 Hook。

© www.soinside.com 2019 - 2024. All rights reserved.