反应空状态-setState

时间:2020-04-06 17:34:43

标签: javascript reactjs material-ui

我删除了进口商品,因为它们没有问题

在渲染中,我设置了状态,并在控制台中将其显示给我,但是当我尝试对其进行映射时,它为null,它告诉我状态“ allInfo”中没有元素,如何我可以解决此错误,以便更新状态吗?

class Friends扩展了组件{

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>
);

} }

导出默认朋友

2 个答案:

答案 0 :(得分:1)

fetch('https://localhost:44314/api/Users')
    .then(response => response.json())
    .then(data => {
        this.setState(prevState => {
            allInfo: data.map((obj) => { prevState.allInfo.push(obj) })
        })
    })

Push返回数组的长度。

您应该使用:

this.setState(prevState => {
            allInfo: data
        })

答案 1 :(得分:0)

很多事情,您正在使用访存,然后,不建议再使用


async render() {

   let response = await fetch('https://localhost:44314/api/Users')
            this.setState(prevState => {
                allInfo: data.map((obj) => { prevState.allInfo.push(obj) })
            })

但要进一步解释您的问题,您所引用的内容不属于then范围,因此您输入的是空值,这会给您带来错误。