反应空状态-setState后状态保持为空 [英] React empty state - State stays null after setState
本文介绍了反应空状态-setState后状态保持为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我删除了进口商品,因为它们没有问题
在渲染中,我设置了状态,并在控制台中将其显示给我,但是当我尝试对其进行映射时,它为null,它告诉我状态"allInfo"中没有元素,如何我可以解决此错误,以便更新状态吗?
In my render, I set my state and it shows it to me in the console, but when I try to map it, it is null and it says to me that there are no elements in the state "allInfo", how can I fix this error so that my state updates?
class Friends扩展了组件{
class Friends extends Component {
constructor(props) {
super(props)
this.state = {
allInfo: []
}
}
render() {
fetch('https://localhost:44314/api/Users')
.then(response => response.json())
.then(data => {
this.setState(prevState => {
allInfo: data.map((obj) => { prevState.allInfo.push(obj) })
})
})
return (
<div>
<NavMenu />
<div style={{ fontSize: 38, textAlign: "center", color: "white" }}>FRIENDS</div>
<TableContainer component={Paper}>
<Table aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Users</TableCell>
<TableCell align="right">Follow</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.state.allInfo.map((row) => (
<TableRow key={row.username}>
<TableCell component="th" scope="row">
{row.username}
</TableCell>
<TableCell align="right">Follow?</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</div>
);
}}
导出默认好友
推荐答案
fetch('https://localhost:44314/api/Users')
.then(response => response.json())
.then(data => {
this.setState(prevState => {
allInfo: data.map((obj) => { prevState.allInfo.push(obj) })
})
})
Push返回数组的长度.
Push returns the length of the array.
您应该使用:
this.setState(prevState => {
allInfo: data
})
这篇关于反应空状态-setState后状态保持为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文