React Redux不更新状态

时间:2019-11-21 19:32:32

标签: javascript reactjs typescript redux

我正在使用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'
    };

store / actions / index.ts

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

store / reducers / index.ts

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

const app = combineReducers({
    category
});

export default app;

store / 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;

我确定我缺少一些小细节。

1 个答案:

答案 0 :(得分:1)

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

store / 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;