[英]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.我是 react 和 redux 的新手,我正在使用 axios,我能够从 api 获取数据,我通过在控制台中打印它来看到它,但不确定如何将数据加载到表中。
The table code is in sports/index.js and axios code is in actions/index.js I provide code and stackblitz here .表格代码在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' },
];
Can you tell me how to fix it?你能告诉我如何解决吗?
try this https://stackblitz.com/edit/react-redux-realworld-gdytzz?file=components%2FSports%2Findex.js试试这个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.我添加了一个连接以确保您的组件已连接到 redux 状态。
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.我还为 React 状态添加了 willReceiveProps 以在获取数据时更改。
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.您可能需要根据您的要求更改要显示的数据,但现在正在显示获取的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.