【发布时间】: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