[英]React not displaying data after successful fetch
我是 React 的新手,并试图弄清楚我当前获取数据并将数据显示到页面的方法出了什么问题。
我通过 Postman 运行后端请求,它似乎可以工作,但是无论出于何种原因,数据都没有映射到我的 state 'list' 数组。 我已经通过控制台记录了 res 并且可以看到数据正在传递给这个组件,但是 state 'list' 映射出了点问题。 任何帮助,将不胜感激。
class Software extends Component {
constructor(props){
super(props)
this.state = {
list : []
}
}
//when componenet is successfully called pull appropriate data
componentDidMount(){
this.getSoftware();
}
//set pulled data to the form of the list
S_List = () => {
return this.state.list.map((curr, index) => {
return < itemlist list = {curr} key = {index} />
})
}
//pull data from the DB
getSoftware(){
fetch(`http://localhost:5000/routes/software`) //need to complete queries
.then(res => res.json())
.then(res => console.log(res)) //
.then(list => this.setState({list}))
.catch(err => console.log(err))
//console.log(this.state);
}
render() {
//console.log(this.state);
return(
<Fragment>
<Link to="/">
<Navbar bg="dark" variant="dark">
<Navbar.Brand href="#home">Ninventory</Navbar.Brand>
</Navbar>
</Link>
<Jumbotron>
<h1>Software</h1>
<p>
This page holds software products like the latest games in the Nintendo library
</p>
</Jumbotron>
<Container bg = "#f72525">
<Table style = {{color:"#f72525"}} striped hover >
<p>contains place holders for now</p>
<br></br>
<thead>
<td>Product</td>
<td>Price</td>
<td>Release Date</td>
</thead>
<tbody>
{this.S_List()}
</tbody>
</Table>
</Container>
</Fragment>
)
}
}
const itemlist = item => (
<tr>
<td>{item.list.s_prodName}</td>
<td>{item.list.s_price}</td>
<td>{item.list.s_releasedate}</td>
</tr>
)
将.then(res => console.log(res))
更改为.then(res => { console.log(res); return res; }
。如果您发布的代码是准确的,您的 console.log 正在吃掉您的响应 object然后将 undefined 传递给 next.then 语句。
在S_List()
方法this.state.list
是一个对象数组。 当您遍历它们时,您已经传递了列表项:
// set pulled data to the form of the list
S_List = () => {
return this.state.list.map((item, index) => {
return <ItemList item={item} key={index} />;
});
};
所以ItemList
组件接收这些项目对象作为道具并且那里没有list
属性(如果您发布的图像是获取的响应):
const ItemList = ({item}) => (
<tr>
<td>{item.s_prodName}</td>
<td>{item.s_price}</td>
<td>{item.s_releasedate}</td>
</tr>
);
并确保在 thenables 中返回res
:
.then(res => {
console.log(res);
return res;
})
.then(list => this.setState({list}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.