redux - 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)
}
解决方案
我发现了错误。出于某种原因,我不得不在 render() 方法中调用 this.props.events 而不是 componentwillmount。
推荐阅读
- synchronization - Unison 星型拓扑:假设被动节点没有变化
- android - ViewModel:回调 onChanged - 在整数 19 之后不显示更改的值,直到值回落到 19 以下
- php - 条件登录重定向
- python - 有赢家时如何打破循环?
- c# - c#omnisharp intellisense 不能在 vscode (windows 10) 中使用 net 5.0
- javascript - 如何使用严格模式而不在 JSlint 中出错
- c++ - 不能将 uint64_t 与 rdrand 一起使用,因为它需要 unsigned long long,但 uint64_t 被定义为 unsigned long
- sql - Wordpress 表:来自 SQL 数据库的动态表
- image - GatsbyImage 用于从 json 文件读取的 url
- python - 数组的符号导数