首页 > 解决方案 > 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(),但也没有帮助。

标签: javascriptreactjsredux

解决方案


我相信你的问题是你导出你的Categories课程两次,一次连接,另一个没有。

如果您从 中删除导出export class Categories extends Component它是否按预期工作?


推荐阅读