Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

I added a connect to make sure your component was connected to the redux state.

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

the connect:

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

I also added a willReceiveProps for the React state to change when the data is fetched.

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

All the fields which you statically defined don't match with the response, so I have tried doing the best I can for filling the table data with the fetch data.

changed the static data to this:

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

you might need to change the data to be shown as per your requirement, but the fetched data now is being shown.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...