首页 > 解决方案 > 向减速器分派操作时无法更新状态

问题描述

我在我的主页组件上,我需要在其中显示文章提要,为此,我必须拥有articleList数组。但是由于某种原因,当我查看商店时,articleList为空。此外,我在获取数据后放置的console.log也无法正常工作。这一切似乎都很奇怪。

Home.js


import React, { Component } from "react"
import { connect } from "react-redux"
import { listAllArticles } from "../actions/articles"

class Home extends Component {

    componentDidMount() {
        this.props.dispatch(listAllArticles)
    }

    render() {
        console.log(this.props)
        return (
            <div style={{ textAlign: "center" }}>
                <h1>Conduit</h1>
                <h5>A place to share your knowledge</h5>
            </div>
        )
    }
}

const mapStateToProps = (state) => {
    return state
}

export default connect(mapStateToProps)(Home)
listAllArticles


export const listAllArticles = () => {
    console.log("inside listAllArticles action creator")
    return dispatch => {
        fetch("https://conduit.productionready.io/api/articles")
            .then(res => res.json())
            .then(data => {
                console.log(data.articles)
                dispatch({
                    type: "LIST_ALL_ARTICLES",
                    data: data.articles
                })
            })
    }
}
articleReducer


const initState = {
    articleList: null
}


export const articleReducer = (state=initState, action) => {
    console.log("inside article reducer")
    switch(action.type) {
        case "LIST_ALL_ARTICLES":
            return {...state, articleList: action.data}
        default:
            return state
    }
}

标签: reactjsreduxredux-thunk

解决方案


推荐阅读