当状态不变时,Redux保持重新渲染

时间:2020-06-18 04:44:26

标签: javascript reactjs redux redux-saga

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

我了解到只有在组件状态发生变化时才触发React重新渲染。

但是我现在很困惑。

因为状态没有更改,但是组件每1-3秒重新呈现一次。 Fully matched data

我尝试了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
);

1 个答案:

答案 0 :(得分:2)

您正在功能组件主体内调用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 />;
};