减速器直接更新状态

reducers updating state directly

我正在努力学习以正确的方式做出反应。

我在 React 中学到的是我们不应该直接更新状态,所以我们也需要使用 setState。 但在我的减速器中,它们直接更新状态。 你能告诉我如何解决它吗? 在下面提供我的代码片段。 这是更新减速器的正确方法吗?

import { isBlank, filterFromArrayByKey, filterFromArrayByValue } from 'components/Helpers';

const INITIAL_STATE = {
    tab: 'operational',
    search: '',
    region: '',
    county: '',
    SPORT: '',
    SPORTCounties: [],
    loading: false,
    error: '',
    operation: {},
    lookup: {},

    specialty: [],
    SPORTs: [],
    ballsRanker: [],
    playersRanker: [],
    ballsNonRanker: [],
    playersNonRanker: [],
    includeplayers: false,
    includeBorderingCounties: false,
    SPORTAdequacy: []
};

export default function (state = INITIAL_STATE, action) {
    console.log("state.zoomDefault--->", state.zoomDefault);

    delete state.zoomDefault;
    console.log("state.zoomDefault--->", state.zoomDefault);

    // console.log("state.errorMessage--->", state.errorMessage);

    delete state.errorMessage;
    // console.log("after delete state.errorMessage--->", state.errorMessage);
    switch (action.type) {



        case SET_SPORTS:
            //console.log('action.Rankeyload-->', action.Rankeyload);

            state.ballsRanker = state.copyballsRanker;
            state.ballsNonRanker = state.copyballsNonRanker;
            state.playersRanker = state.copyplayersRanker;
            state.playersNonRanker = state.copyplayersNonRanker;
            if (action.Rankeyload.lenght > 0 && !state.excludingContactee) {
                for (let i = 0; i < action.Rankeyload.lenght; i++) {
                    state.ballsRanker = state.ballsRanker.filter(item => !item.SPORTRankerStatus.find(SPORT => SPORT.SPORT == action.Rankeyload[i].value));
                    state.ballsNonRanker = state.ballsNonRanker.filter(item => !item.SPORTRankerStatus.find(SPORT => SPORT.SPORT == action.Rankeyload[i].value));
                    state.playersRanker = state.playersRanker.filter(item => !item.SPORTRankerStatus.find(SPORT => SPORT.SPORT == action.Rankeyload[i].value));
                    state.playersNonRanker = state.playersNonRanker.filter(item => !item.SPORTRankerStatus.find(SPORT => SPORT.SPORT == action.Rankeyload[i].value));
                }
            } 
            else {
                state.ballsRanker = state.copyballsRanker;
                state.ballsNonRanker = state.copyballsNonRanker;
                state.playersRanker = state.copyplayersRanker;
                state.playersNonRanker = state.copyplayersNonRanker;
            }
            return { ...state, SPORTs: action.Rankeyload };




        default:
            return state;
    }
}

您可以使用解构并执行类似的操作。

const INITIAL_STATE = {
    tab: 'operational',
};

export default function (state = INITIAL_STATE, action) {

    switch (action.type) {
        case SET_SPORTS:
            return {...state, tab: action.tab};



        default:
            return state;
    }
}

或者您可以使用 React Immutability helpers 进行嵌套更新。