首页 > 解决方案 > 操作不会触发 redux/redux thunk

问题描述

所以基本上,我正在调用从后端获取用户的 loadUser,它始终可以正常工作,但是每当我刷新仪表板页面时,它都不会触发任何操作,即使我会尝试在仪表板页面中的 useEffect 内调用 loadUser ,仍然没有任何动作被触发并且我无权访问用户,这是我需要的,因为我必须有权访问用户 ID。我也在使用 redux thunk,我听说确实存在副作用,但我仍然真的很想得到帮助:)

我将链接下面的 github 存储库并粘贴似乎与此问题相关的代码。如果您确实需要更多代码,repo 也在这里:

https://github.com/tigerabrodi/eBuy

仪表板组件

import React, {useEffect, Fragment, useState} from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import Pagination from '../products/Pagination';
import ProductItem from '../products/ProductItem';
import { getUserProducts } from '../../redux/product/product.actions';
import {loadUser} from "../../redux/auth/auth.actions";

const Dashboard = ({product: {products, loading, totalProducts}, loadUser, getUserProducts, auth: {user}}) => {


    const [currentPage, setCurrentPage] = useState(1);
    const [productsPerPage] = useState(6);
    const paginate = pageNumber => setCurrentPage(pageNumber);
        useEffect(() => {
        getUserProducts(user._id, currentPage);
    }, [currentPage, getUserProducts, user._id]);

    return (
        <Fragment>
        <div className="container">
            <div className="row">
                <div className="col text-center">
                <h1 className="text-monospace text-info display-2">Dashboard</h1>
                <Link to="/add-product" className="btn btn-block btn-warning">Add Product <i className="far fa-money-bill-alt" /> </Link>
                </div>
            </div>
        </div>
        <br />
        <div className="container">
        <div className="row">
        {products.map(product => (
            <div className="col-md-4 col-6">
                <ProductItem key={product._id} product={product} /> 
            </div>
        ))};
        <div className="col-12">
        {products && (
                    <Pagination productsPerPage={productsPerPage} totalProducts={totalProducts} paginate={paginate} />
        )}
        </div>
        </div>
        </div>
        </Fragment>
    );
}

const mapStateToProps = state => ({
    product: state.product,
    auth: state.auth
})

export default connect(mapStateToProps, {getUserProducts, loadUser})(Dashboard);

授权减速器

import {AuthActionTypes} from "./auth.types";


const initialState = {
    token: localStorage.getItem("token"),
    isAuthenticated: null,
    loading: true,
    user: null
}


const authReducer = (state = initialState, action) => {
    const {type, payload} = action;
    switch (type) {
        case AuthActionTypes.USER_LOADED:
          return {
            ...state,
            isAuthenticated: true,
            loading: false,
            user: payload
          };
        case AuthActionTypes.REGISTER_SUCCESS:
        case AuthActionTypes.LOGIN_SUCCESS:
          localStorage.setItem('token', payload.token);
          return {
            ...state,
            ...payload,
            isAuthenticated: true,
            loading: false
          };
        case AuthActionTypes.REGISTER_FAIL:
        case AuthActionTypes.AUTH_ERROR:
        case AuthActionTypes.LOGIN_FAIL:
        case AuthActionTypes.LOGOUT:
        case AuthActionTypes.ACCOUNT_DELETED:
          case AuthActionTypes.USER_ERROR:
          localStorage.removeItem('token');
          return {
            ...state,
            token: null,
            isAuthenticated: false,
            loading: false
          };
        default:
          return state;
    }
}

export default authReducer

身份验证操作

import axios from "axios";
import {setAlert} from "../alert/alert.actions"
import {AuthActionTypes} from "./auth.types"
import setAuthToken from "../../utils/setAuthToken"

// Load User
export const loadUser = () => async dispatch => {
    if (localStorage.token) {
      setAuthToken(localStorage.token);
    }

    try {
      const res = await axios.get('/auth');

      dispatch({
        type: AuthActionTypes.USER_LOADED,
        payload: res.data
      });
    } catch (err) {
      dispatch({
        type: AuthActionTypes.AUTH_ERROR
      });
    }
  };

// Register User
export const register = ({ name, email, password }) => async dispatch => {
    const config = {
      headers: {
        'Content-Type': 'application/json'
      }
    };

    const body = JSON.stringify({ name, email, password });

    try {
      const res = await axios.post('/auth/signup', body, config);

      dispatch({
        type: AuthActionTypes.REGISTER_SUCCESS,
        payload: res.data
      });

      dispatch(loadUser());
    } catch (err) {
      const errors = err.response.data.errors;

      if (errors) {
        errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
      }

      dispatch({
        type: AuthActionTypes.REGISTER_FAIL
      });
    }
  };

    // Login User
export const login = (email, password) => async dispatch => {
    const config = {
      headers: {
        'Content-Type': 'application/json'
      }
    };

    const body = JSON.stringify({ email, password });

    try {
      const res = await axios.post('/auth/signin', body, config);

      dispatch({
        type: AuthActionTypes.LOGIN_SUCCESS,
        payload: res.data
      });

      dispatch(loadUser());
    } catch (err) {
      const errors = err.response.data.errors;

      if (errors) {
        errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
      }

      dispatch({
        type: AuthActionTypes.LOGIN_FAIL
      });
    }
  };

    // Logout / Clear Profile
export const logout = () => dispatch => {
    dispatch({ type: AuthActionTypes.LOGOUT });
  };

标签: javascriptreactjsreduxreact-reduxredux-thunk

解决方案


推荐阅读