gpt4 book ai didi

javascript - TypeError : this. state.screams。不是函数 js 与 fire base react

转载 作者:行者123 更新时间:2023-11-30 13:55:59 25 4
gpt4 key购买 nike

这是我的代码

请大家帮我解决这个问题

import React, { Component } from 'react'
import Grid from '@material-ui/core/Grid';
import axios from 'axios';
class home extends Component {

state = {
screams:null
}

//screams: [] also not working

componentDidMount(){
axios.get('/screams')
.then(res =>{
this.setState({
screams: res.data
})
})
.catch(err =>{
console.log(err)
})
}

render() {
let recentScreams = this.state.screams ? (
this.state.screams.map(scream => <p>{scream.body}</p>)
) : <p>loading ....</p>
return (
<Grid container spacing={16}>
<Grid item sm={8} xs={12}>
{recentScreams}
</Grid>
<Grid item sm={4} xs={6}>
<p>profile ....</p>
</Grid>
</Grid>
)
}
}

export default home;

错误是

TypeError: this.state.screams.map is not a function

 19 | }
20 |
21 | render() {
> 22 | let recentScreams = this.state.screams ? (
| ^ 23 | this.state.screams.map(scream => <p>{scream.body}</p>)
24 | ) : <p>loading ....</p>
25 | return (

我在这里发布这个问题之前引用了这个问题的答案

1.React JS - Uncaught TypeError: this.props.data.map is not a function

2。 TypeError: this.state.patients.map is not a function

3。 ReactJS: TypeError: this.state.data.map is not a function

4. Uncaught TypeError: s.map is not a function in ReactJs

5. React .map is not a function

这是我的 api/screams 结果

{
"scream": [
{
"screamId": "1WRwEClETpvWRyPADUKh",
"body": "hello all welcome to my site",
"userHandle": "image",
"createAt": "2019-07-25T05:39:52.099Z",
"userImage": "https://firebasestorage.googleapis.com/v0/b/demoapp-c1dab.appspot.com/o/no-img-test.png?alt=media"
},
{
"screamId": "csFCMA4wY3NXuKpZAVr8",
"body": "oops everything working pass 7",
"userHandle": "newapi",
"createAt": "2019-07-22T07:21:32.964Z"
},
{
"screamId": "Kit3XcAEFu8DWOE4IoXJ",
"body": "hello world from no token",
"userHandle": "Ghost",
"createAt": "2019-07-21T17:00:00.091Z"
}
]
}

最佳答案

在获取数据之前,您的变量将被设置为 null,从而导致您在第一次渲染时出错。

首先尝试将变量设置为空数组:

state = {
screams: []
}

刚刚看到您获取的数据。我认为您需要获取 JSON 响应中的数组:

this.setState({
screams: res.data.scream
})

代替:

this.setState({
screams: res.data
})

关于javascript - TypeError : this. state.screams。不是函数 js 与 fire base react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57304780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com