gpt4 book ai didi

javascript - ReactJS:Redux 状态没有改变

转载 作者:行者123 更新时间:2023-12-01 01:16:47 25 4
gpt4 key购买 nike

我刚刚开始使用 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));
};

reducers/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;
}
}

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

reducer /index.js

import { combineReducers } from "redux";
import categories from './categories';

export default combineReducers({
categories,

});

使用remote-redux-devtools,我在我的状态中从未见过任何东西。目前上面的代码给了我 3 个错误,其中两个是

this.props.getCategories is not a function

我的猜测是,因为 Categories 类存在一些问题,它没有传递任何内容到状态,这可能是错误的根本原因。我又遇到了一个错误,连接到 Categories 时未使用属性调用,但出于调试目的,我在那里放置了空数组 - 一个错误消失了,但仅此而已。我还尝试将构造函数添加到 Categories 并调用 super(),但也没有帮助。

最佳答案

我相信您的问题是您将 Categories 类导出两次,一次连接,另一次则不连接。

如果从 export classcategories extends Component 中删除export,它是否能按预期工作?

关于javascript - ReactJS:Redux 状态没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54679305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com