【发布时间】:2019-12-09 19:13:06
【问题描述】:
这是我的代码
请任何人帮我解决这个问题
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 不是函数
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"
}
]
}
【问题讨论】:
-
该错误仅表示
this.state.screams为空或状态中没有数据。您正在尝试对空数据使用map函数 -
您是否使用调试器/控制台验证了
this.state.screams的值? -
您设置了错误的数据。尝试设置
res.data.scream。
标签: javascript reactjs firebase