[英]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.