首页 > 解决方案 > 即使在提供了第二个空数组参数之后,是否有任何方法可以停止 useEffect 无限循环?

问题描述

我尝试从我的 React 应用程序中的 useEffect 挂钩调用调度方法,但在渲染 useEffect 后继续循环。这是我的代码....

category.actions.js 这里是执行的动作

import axios from "../../apiFetch/axios";
import { categoryActions } from './constants';


export const getCategories = () => {

  return async (dispatch) => {

    dispatch({ type: categoryActions.GET_CATEGORY_ACTION})

    const res = await axios.get('/category/getCategories');
    console.log(res)

    if(res.status === 200){
      const {categoryList} =  res.data;
      dispatch({
        type: categoryActions.GET_CATEGORY_SUCCESS,
        payload: {
          categories: categoryList
        }
      });
    }else{
      dispatch({
        type: categoryActions.GET_CATEGORY_FAILURE,
        payload: {
          error: res.data.error
        }
      });
    }
  }
}

category.reducer.js 这是reducer代码 import { categoryActions } from "../actions/constants";

const initialState = {
  laoding: false,
  categoryList: [],
  error: null
}

const categoryReducer = (state = initialState, action) => {
  switch(action.type){
    case categoryActions.GET_CATEGORY_ACTION:
      return{
        loading: true
      };
    case categoryActions.GET_CATEGORY_SUCCESS:
      return{
        loading: false,
        categoryList: action.payload.categories
      };
    case categoryActions.GET_CATEGORY_FAILURE:
      return{
        loading: false,
        error: action.payload.error
      }
    default:
      return{
        ...initialState
      }
  }
}

export default categoryReducer;

我使用 useEffect 挂钩的类别组件

import Layout from '../../components/Layout';
import {Container, Row, Col} from 'react-bootstrap'
import { useDispatch, useSelector } from 'react-redux';
import { getCategories } from '../../redux/actions';

const Category = () => {
  const dispatch = useDispatch();
  const state = useSelector(state => state.categoryReducer)

  useEffect(() => {
    dispatch(getCategories());
  },[]);

  return (
    <Layout sidebar>
      <Container>
        <Row>
          <Col>
            <div style={{display: 'flex', justifyContent: 'space-between'}}>
              <h3>Category</h3>
              <button>Add</button>
            </div>
          </Col>
        </Row>
      </Container>
    </Layout>
  )
}

export default Category;

constant.js 这里是我用作类型的常量

export const categoryActions = {
  GET_CATEGORY_ACTION: 'GET_CATEGORY_ACTION',
  GET_CATEGORY_SUCCESS: 'GET_CATEGORY_SUCCESS',
  GET_CATEGORY_FAILURE: 'GET_CATEGORY_FAILURE'
}

这是 index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {Provider} from 'react-redux';
import store from './redux/store';
import { BrowserRouter as Router } from 'react-router-dom';

window.store = store;
ReactDOM.render(
  <Provider store={store}>
    <Router>
      <React.StrictMode>
        <App />
      </React.StrictMode>
    </Router>
  </Provider>,
  document.getElementById('root')
);
reportWebVitals();

这是 App.js 父组件

import Signin from './containers/Signin';
import Signup from './containers/Signup';
import PrivateRoute from './components/HOC/PrivateRoute';
import {useDispatch, useSelector} from 'react-redux';
import { isUserLogin } from './redux/actions';
import Products from './containers/Products';
import Orders from './containers/Orders';
import Category from './containers/Category';


function App() {
  const auth = useSelector(state => state.authReducer);
  const dispatch = useDispatch();

  useEffect(() => {
    if(!auth.authenticate){
      dispatch(isUserLogin());
    }
  }, [])

  return (
    <div className="App">
      <Switch>
        <PrivateRoute path="/" exact component={Home} />
        <PrivateRoute path="/products"  component={Products} />
        <PrivateRoute path="/orders"  component={Orders} />
        <PrivateRoute path="/category"  component={Category} />
        <Route path="/signup" component={Signup} />
        <Route path="/signin" component={Signin} />
      </Switch>
    </div>
  );
}

export default App;

标签: node.jsreactjsmongodbreduxasync-await

解决方案


推荐阅读