簡體   English   中英

axios 獲取請求並顯示在表格中

[英]axios get requests and displaying in table

我是 react 和 redux 的新手,我正在使用 axios,我能夠從 api 獲取數據,我通過在控制台中打印它來看到它,但不確定如何將數據加載到表中。

表格代碼在sports/index.js 中,axios 代碼在actions/index.js 中,我在這里提供代碼和stackblitz。

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' },
];

你能告訴我如何解決嗎?

試試這個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)))

您可能需要根據您的要求更改要顯示的數據,但現在正在顯示獲取的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM