【问题标题】:API returns data, but Redux doesn't change the stateAPI 返回数据,但 Redux 不改变状态
【发布时间】:2020-03-22 14:09:05
【问题描述】:

我使用 Spring Boot 作为 API,我有一个方法可以从数据库中返回所有文章。它是映射在 /api/articles 上的 GET 方法。 (用 Postman 测试,它可以正常工作)

此外,在使用 Redux 扩展进行检查时,我可以看到文章的状态仅包含占位符文章。

控制台中没有错误。。 同样重要的是,成功调用了 GET_ARTICLES 案例(resp.data 包含所有文章)。

现在在前端,我使用 Redux 来存储文章。这是我的 Reducer 的外观:

import { GET_ARTICLES } from "../actions/types";
import repo from "../repository/axiosRepository";
const InitialState = {
  articles: [
    {
      title: "Lord of the rings",
      author: "JR Talkins",
      content: "lorem ipsum dolor sit amet",
      id: 1
    }
  ]
};

export default function(state = InitialState, action) {
  switch (action.type) {
    case GET_ARTICLES:
      repo.fetchArticles().then(resp => {
        return {
          articles: resp.data
        };
      });
    default:
      return state;
  }
}

这是我想要显示文章的组件:

   import React, { Component } from 'react';
import Article from '../article/Article';
import articleService from '../../repository/axiosRepository';

import { connect } from 'react-redux';
import { getItems } from '../../actions/articleActions';

class HomePage extends Component {
    componentDidMount(){
      this.props.getItems();
    }

    render() {
        let { articles } = this.props.articles;

        return (
            <div className="container">
            <div className="row">
              <div className="col-md-9">
                {articles && articles.map(article => <Article key={article.id} article={article}/>)}
              </div>
              <div className="col-md-3">
                widgets
              </div>
            </div>
        </div>
        )
    }
}

const mapStateToProps = (state) => ({
  articles: state.articles
})
export default connect(mapStateToProps, {getItems})(HomePage);

我不明白为什么用 resp.data 返回对象不会改变状态。

【问题讨论】:

    标签: javascript redux axios reactjs


    【解决方案1】:

    我相信这个问题出在你的减速器上。 repo.fetchArticles() 是一个异步函数,它应该在你的 action creator 中调用,如下所示:

    function getItems() {
      repo.fetchArticles().then(resp => {
         return {
           type: GET_ARTICLES
           payload: resp.data
         };
       });
    }
    

    在你的 action creator 中获取数据,并使用已经获取的数据调用 reducer。

    case GET_ARTICLES:
          return { articles: action.payload };
    

    【讨论】:

      猜你喜欢
      • 2018-08-09
      • 2019-01-30
      • 2018-12-31
      • 2019-02-20
      • 2019-04-29
      • 2020-12-07
      • 2021-04-03
      • 1970-01-01
      • 2019-03-19
      相关资源
      最近更新 更多