【问题标题】:Redux keeps re-rendering when state doesn't change当状态没有改变时,Redux 会不断重新渲染
【发布时间】:2020-06-18 04:44:26
【问题描述】:

我正在制作我的第一个 React-Redux 项目。

我学会了 React 仅在组件的状态发生变化时才被触发时重新渲染。

但我现在很困惑。

因为状态没有改变,但组件每 1 到 3 秒重新渲染一次。

我尝试了 shallowEqual,但没有成功。

为什么会这样?

// container
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';

import Home from 'presentations/Home';
import * as homeActions from 'modules/home';

const HomeContainer = () => {
    const dispatch = useDispatch();
    const list = useSelector(state => state.home.list);

    dispatch(homeActions.getList());

    console.log(list);

    return (
        <Home
        />
    );
}

export default HomeContainer;
// Redux module
import axios from 'axios';
import { call, put, takeEvery } from 'redux-saga/effects';
import { createAction, handleActions } from 'redux-actions';

function getListAPI() {
    return axios.get('http://localhost:8000/');
}

const GET_LIST         = 'home/GET_LIST';
const GET_LIST_SUCCESS = 'home/GET_LIST_SUCCESS';
const GET_LIST_FAILURE = 'home/GET_LIST_FAILURE';

export const getList = createAction(GET_LIST);

function* getListSaga() {
    try {
        const response = yield call(getListAPI);
        yield put({ type: GET_LIST_SUCCESS, payload: response });
    } catch (e) {
        yield put({ type: GET_LIST_FAILURE, payload: e });
    }
}

const initialState = {
    list: []
};

export function* homeSaga() {
    yield takeEvery('home/GET_LIST', getListSaga);
}

export default handleActions(
    {
        [GET_LIST_SUCCESS]: (state, action) => {
            const temp = action.payload.data;
            return {
                list: temp
            };
        }
    }, initialState
);

【问题讨论】:

    标签: javascript reactjs redux redux-saga


    【解决方案1】:

    您在功能组件主体内调用dispatch = useDispatch();,这会更新导致重新渲染的状态list,然后执行您的dispatch = useDispatch();,依此类推。

    在 useEffect 中发送您的操作以解决问题

    const HomeContainer = () => {
      const dispatch = useDispatch();
      const list = useSelector((state) => state.home.list);
      useEffect(() => { //<---like this
        dispatch(homeActions.getList());
      }, []);
    
      console.log(list);
    
      return <Home />;
    };
    
    

    【讨论】:

      猜你喜欢
      • 2020-01-20
      • 2020-04-22
      • 2018-12-31
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      • 2019-05-22
      • 2021-06-12
      • 1970-01-01
      相关资源
      最近更新 更多