首页 > 解决方案 > redux 状态没有改变

问题描述

我使用的是 Net Core、React-Redux 样板,当我运行 fetch api 操作时,reducer 状态根本没有改变。

这是我的行动

import axios from "axios";
import config from '../config';

const ROOT_URL = config[process.env.NODE_ENV].api;

export const FETCH_EVENTS = "FETCH_EVENTS";
export function fetchEvents() {
    const url = ROOT_URL +"/Event/GetAllEvents";
    const request = axios.get(url);

    return {
        type: FETCH_EVENTS,
        payload: request
    };
}

我的索引减速器:

import { combineReducers} from 'redux';
import { routerReducer } from 'react-router-redux';
import dataReducer from './dataReducer'

    const reducers = {
        events: dataReducer
    };

const rootReducer = combineReducers({
    ...reducers,
    routing: routerReducer
});

export default rootReducer;

和我的减速机:

import { FETCH_EVENTS } from "../actions/ExtractActions";

export default function (state = [], action) {
    switch (action.type) {
        case FETCH_EVENTS:
            console.log("inside reducer")
            return [action.payload, ...state];
    }
    return state;
}

所以我在 Home 组件中添加了这段代码:

function mapDispatchToProps(dispatch) {
    return bindActionCreators({ fetchEvents }, dispatch);
}

function mapStateToProps(state) {
    return {
        events: state.events
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(Home);

但是当我尝试运行该操作并尝试查看减速器状态是否已更改时,我会在控制台上为“this.props.events”记录一个空数组。即使我试图将api数据存储到状态,我什至尝试修改reducer方法并简单地返回一个字符串,但是this.props.events再次返回一个空数组[]。我猜我的 redux 不工作,但我不知道为什么。我整晚都在调试

componentWillMount() {
    this.props.fetchEvents()
    console.log(this.props.events)

}

标签: reduxreact-redux

解决方案


我发现了错误。出于某种原因,我不得不在 render() 方法中调用 this.props.events 而不是 componentwillmount。


推荐阅读