当React Hooks中的redux状态改变时,道具不更新

Ert*_*ani 5 state reactjs redux react-redux

我正在尝试在React Hooks项目上实现Redux,但它似乎没有很好的工作。我在这里做错什么了吗?

reducer.js

const initialState = {
    educations: []
};

export default function home(state = initialState, action){
    switch(action.type){
        case GET_EDUCATIONS: {
            state.educations = action.payload;
            return state;
        }
        default:
            return state;
    }
}
Run Code Online (Sandbox Code Playgroud)

action.js

import * as types from '../constans/home';

export const getEducations = () => {
    return dispatch => {
        const edus = [
            {value: 1, name: 'Bachelor'},
            {value: 2, name: "Master"}
        ]

        dispatch({
            type: types.GET_EDUCATIONS,
            payload: edus
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

零件

import React, {useEffect} from 'react';
import {connect} from 'react-redux';
import {getEducations} from '../../redux/actions/home';

function Header({educations, getEducations}) { 
    useEffect(() => {
        getEducations(); //calling getEducations()
    }, [])

    useEffect(() => {
        console.log(educations) //console educations after every change
    })

    return (
        <div className="main-header">
        </div>
    )
}

const mapStateToProps = (state) => {
    return {
        educations: state.home.educations
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        getEducations: () => { dispatch(getEducations())}
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Header);
Run Code Online (Sandbox Code Playgroud)

而且,Header函数中的Education属性始终是一个空数组,如中所示initialState。当我使用进行浏览器检查时Redux Devtools,它显示状态包含数组中的两个对象。 在此处输入图片说明

因此,无论是否更改redux状态,该组件的属性都将保持为initialState。

Chr*_*Ngo 9

在 中redux,您应该避免直接改变减速器的状态。不要做类似的事情state.reducers = blah。为了redux知道您正在尝试更新state,您需要返回一个全新的状态对象。遵循这些原则,您的减速器将正确更新,您的组件将获得新数据。

减速器.js

const initialState = {
    educations: []
};

export default function home(state = initialState, action){
    switch(action.type){
        case GET_EDUCATIONS: {
            return {
               ...state,
               educations: action.payload
            };
        }
        default:
            return state;
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我们返回一个新的状态对象。它将包括现有的所有内容state,因此...state,我们只需educations使用action.payload.