【发布时间】:2019-12-11 23:50:15
【问题描述】:
我正在尝试在 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;
}
}
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
})
}
}
组件
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);
并且Header函数中的education属性总是一个空数组,如initialState。
当我使用Redux Devtools 检查浏览器时,它显示状态包含数组中的这两个对象。
所以无论我是否改变 redux 状态,组件的属性都将保持初始状态。
【问题讨论】:
-
您介意将其放入 CodeSandbox 中吗?
-
@ErtanHasani,请参阅下面的解决方案,让我知道这是否适合您 :)
标签: reactjs redux react-redux state