【问题标题】:React Redux not updating stateReact Redux 不更新状态
【发布时间】:2019-11-21 19:32:32
【问题描述】:

我正在使用 React-Redux 的 React Hooks 实现。下面是我的代码流程。由于某种原因,我在我的 dispatch(fuction(value)) 中传递的任何值都没有在我的减速器中检测到。我想不通。

src/components/categories/selectCategory.tsx

    import React from 'react';
    import {useDispatch} from 'react-redux';
    import {setCategory} from '../../store/actions';

    const selectCategory = (name: string) => {
        dispatch(setCategory(name)); // ex: name = 'algebra'
    };

存储/操作/index.ts

export const setCategory = (name) => ({
    type: 'SET_CATEGORY',
    name: name
});

存储/reducers/index.ts

import {combineReducers} from 'redux';
import category from './category';

const app = combineReducers({
    category
});

export default app;

存储/reducers/category.ts

const initialState = {
    name: 'calculus'
};

const category = (state = initialState, action) => {
    switch (action.type) {
        case 'SET_CATEGORY':
            return {name: state.name}; // outputs 'calculus'
        default:
            return state;
    }
};

export default category;

我确定我遗漏了一些小细节。

【问题讨论】:

  • 在你的 reducer 中返回 action.name
  • @ducmai 可以,谢谢

标签: javascript reactjs typescript redux


【解决方案1】:

我的问题已通过返回 action.name 属性而不是 state.name 得到解决。

存储/reducers/category.ts

const initialState = {
    name: 'calculus'
};

const category = (state = initialState, action) => {
    switch (action.type) {
        case 'SET_CATEGORY':
            return {name: action.name};
        default:
            return state;
    }
};

export default category;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 2022-08-17
    • 2021-01-08
    相关资源
    最近更新 更多