javascript - ReactJS:Redux 状态没有改变
问题描述
我刚从 React 和 Redux 开始,偶然发现了一些我自己无法弄清楚的事情——我认为Redux 状态没有改变,它会导致(一些)错误。我正在使用 remote-redux-devtools@0.5.0 检查状态。我的代码:
分类.js:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { getCategories } from '../../actions/categories';
export class Categories extends Component {
static propTypes = {
categories: PropTypes.array.isRequired
};
componentDidMount() {
this.props.getCategories();
}
render() {
return (
<div>
Placeholder for categories.
</div>
)
}
}
const mapStateToProps = state => ({
categories: state.categories.categories
});
export default connect(mapStateToProps, { getCategories })(Categories);
../../actions/categories.js:
import axios from "axios";
import { CATEGORIES_GET } from "./types";
export const getCategories = () => dispatch => {
return axios
.get("/api/notes/categories/")
.then(res => {
dispatch({
type: CATEGORIES_GET,
payload: res.data
});
})
.catch(err => console.log(err));
};
减速器/categories.js:
import { CATEGORIES_GET } from '../actions/types.js';
const initialState = {
categories: []
};
export default function (state = initialState, action) {
switch (action.type) {
case CATEGORIES_GET:
return {
...state,
categories: action.payload
};
default:
return state;
}
}
商店.js:
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'remote-redux-devtools';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const initialState = {};
const middleware = [thunk];
const store = createStore(
rootReducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware)));
export default store;
减速器/index.js
import { combineReducers } from "redux";
import categories from './categories';
export default combineReducers({
categories,
});
使用 remote-redux-devtools,我在我的状态下从未见过任何东西。目前,上面的这段代码给了我 3 个错误,其中两个是
this.props.getCategories 不是函数
我的猜测是,因为类存在一些问题Categories
,它没有将任何东西传递给状态,这可能是错误的根本原因。我还有一个错误,与Categories
未使用属性调用有关,但出于调试目的,我将空数组放在那里 - 一个错误消失了,但就是这样。我也尝试将构造函数添加到Categories
并调用super()
,但也没有帮助。
解决方案
我相信你的问题是你导出你的Categories
课程两次,一次连接,另一个没有。
如果您从 中删除导出,export class Categories extends Component
它是否按预期工作?
推荐阅读
- c# - Castle Winsdor - 通过类型化工厂传递的传播依赖项
- angular - 仅向 *ngFor 广播增量更改?
- python - 在 python/selenium 中检查代理
- r - 根据 data.frame 中每组的 xy 坐标计算斜率
- python-3.x - 如何从python中的二维列表中选择一些在第0位具有相同值的项目
- android - 如果 ArrayList 中存在世界,Android SQLite 忽略添加
- java - 将 jdk 源代码添加到我现有的 Java EE Eclipse (Photon)
- java - android显示后如何在自定义对话框中更改视图的可见性
- html - 仅当前一个文件输入不为空时才显示文件输入
- postgresql - 如何连接两个表并创建新列?