首页 > 解决方案 > axios get requests and displaying in table

问题描述

I am new to react and redux, I'm using axios, I am able to fetch the data from the api, I saw it by printing it in console, but not sure how to load the data in the table.

The table code is in sports/index.js and axios code is in actions/index.js I provide code and stackblitz here.

export const fetchAllPosts = () => {
  return (dispatch) => {
    return axios.get(apiUrl)
      .then(response => {
                console.log("fetchAllPosts.response.data--->", response.data);

        dispatch(fetchPosts(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};



const rows = [
  { id: 'name', numeric: false, disablePadding: true, label: 'Gender' },
  { id: 'shortname', numeric: true, disablePadding: false, label: 'Name' },
  { id: 'description', numeric: false, disablePadding: true, label: 'Location' },
  { id: 'order', numeric: true, disablePadding: false, label: 'Phone' },
  { id: 'code', numeric: true, disablePadding: true, label: 'Picture' },
  { id: 'active', numeric: true, disablePadding: true, label: 'Nat' },
];

Can you tell me how to fix it?

标签: javascriptreactjsapireduxaxios

解决方案


试试这个 https://stackblitz.com/edit/react-redux-realworld-gdytzz?file=components%2FSports%2Findex.js

我添加了一个连接以确保您的组件已连接到 redux 状态。

const mapStateToProps = (state) => {
  return {
    posts: state.posts
   }
 }

连接:

 export default withRouter(connect(mapStateToProps, {})(withStyles(styles)(EnhancedTable)));

我还为 React 状态添加了一个 willReceiveProps 以在获取数据时进行更改。

componentWillReceiveProps(nextProps){
 if (this.props.posts !== nextProps.posts) {
   this.setState({data: nextProps.posts})
  }
 }

您静态定义的所有字段都与响应不匹配,因此我已尽力使用获取数据填充表数据。

将静态数据更改为:

data: [...((this.props.posts || []).map((x, i) => createData(i, x.name, x.name.first, x.description || "description", x.order || 1, x.code, x.active)))

您可能需要根据您的要求更改要显示的数据,但现在正在显示获取的数据。


推荐阅读