Reactjs 如何在React JS的主页上显示表格?
我有一个class.js可以从Reactjs 如何在React JS的主页上显示表格?,reactjs,axios,Reactjs,Axios,我有一个class.js可以从axios.get('api/info/GetTableList')输出表。但它把它画上了新的一页。如何在主页上显示表格 import React, { Component } from 'react'; import axios from 'axios'; export class Info extends Component { static displayName = Info.name; constructor(props) {
axios.get('api/info/GetTableList')
输出表。但它把它画上了新的一页。如何在主页上显示表格
import React, { Component } from 'react';
import axios from 'axios';
export class Info extends Component {
static displayName = Info.name;
constructor(props) {
super(props);
this.state = { data: [] };}
componentDidMount() {
axios.get('api/info/GetTableList ').then((res) => {
this.setState({ data: res });
})
}
render() {
return (
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>IP</th>
<th>WRO</th>
</tr>
</thead>
<tbody>
{this.state.data.map(function (item, key) {
return (
<tr>
<td>{item.id}</td>
<td>{item.ip}</td>
<td>{item.wro}</td>
</tr>
)
})}
</tbody>
</table>
</div>
);
}
}
import React,{Component}来自'React';
从“axios”导入axios;
导出类信息扩展组件{
静态显示名称=Info.name;
建造师(道具){
超级(道具);
this.state={data:[]};}
componentDidMount(){
get('api/info/GetTableList')。然后((res)=>{
this.setState({data:res});
})
}
render(){
返回(
身份证件
知识产权
WRO
{this.state.data.map(函数(项,键){
返回(
{item.id}
{item.ip}
{item.wro}
)
})}
);
}
}
这里的问题是axios将返回响应对象,您需要从响应中获取数据
componentDidMount() {
axios.get('api/info/GetTableList ').then(({data=[]}) => {
this.setState({ data});
})
}
我使用了速记语法,你可以使用普通语法
componentDidMount() {
axios.get('api/info/GetTableList ').then((res) => {
this.setState({ data : res.data});
})
}
另外,请尝试记录res
等
componentDidMount() {
axios.get('api/info/GetTableList ').then((res) => {
console.log(res);
this.setState({ data : res.data});
}).catch(console.error)
}
请共享整个控制台日志您可以使用fetch代替axios
async componentDidMount() {
const res = await fetch(`api/info/GetTableList`)
const data = await res.json();
this.setState({
data
})
}
或者你可以这样使用
async componentDidMount() {
await fetch(
`api/info/GetTableLis`,
{
method: "GET",
}
)
.then(data => data.json())
.then(data => {
this.setState({
data
});
}),
}
我认为你的问题遗漏了一些东西。从代码的角度来看,一切都很好。您的表应该显示在Info
componentint上,它显示但加载在页面顶部,并且标题消失,这意味着您的应用程序结构错误。标题组件应该位于父组件上。或者,您可以在表对象之前插入头组件。当页面第一次加载时,有一个标题和ID IP WRO。通过get重新加载后,页面将被更新,没有任何内容,但是使用了一个表数组。不幸的是,没有任何效果((并且有一种方法不使用axios或componentDidMount()),您可以尝试记录响应,如jsx componentDidMount(){axios.get('api/info/GetTableList')。然后((res)=>{console.log(res)this.setState({data:res.data});}).catch(e=>console.log(e))}