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?
解决方案
试试这个 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)))
您可能需要根据您的要求更改要显示的数据,但现在正在显示获取的数据。
推荐阅读
- python - 如何在 Python3 中访问以下列表和字典值?
- python - 我的脚本在hotels.com 中获得了一个子页面的网址,但该网址又回到了以前的状态
- javascript - keyup 事件未从 textarea 触发
- java - 使用 httpclient 读取文件时连接重置(断开管道)异常
- pytorch - 在 pytorch 张量中将布尔掩码与切片相结合
- .net - .NET Core 运行时和 SDK 版本 - 针对特定的运行时版本?
- javascript - ValueError:块结构必须包含标记的标记或树
- python - 如何将从网站抓取的所有页面导出到 Excel
- java - Maven:将war/web-inf/classes中的类作为jar添加到war/web-inf/lib
- c++ - 导致c++程序运行缓慢的文件系统