繁体   English   中英

React JS:为什么我在 componentdidMount() 中出错?

[英]React JS: Why am I getting error at componentdidMount()?

以下是我的父组件:

const movies = [896, 895]

    const cards = movies.map(movie =>{
        <FlipCard number = {'movie'} />
    })

在子组件中,我试图访问 props.number,但出现错误。 子组件代码:

state = {
        poster: 'http://image.tmdb.org/t/p/w500',
    }

     componentDidMount(){
        axios.get('https://api.themoviedb.org/3/movie/' + {this.props.number} + '?api_key=*******&language=en-US')
            .then(
                    res=>{
                        this.setState({poster: this.state.poster + res.data.poster_path})   
                        console.log(this.props);             
                        }
                )   
        } 

在浏览器中,我收到此错误:在此处输入图像描述[this.props.number 上的意外关键字“this”]

在 VS Code 中,我收到此错误enter image description here [':' expected at that axios line]

我该如何解决这个问题?

编辑:我确实删除了花括号。 现在 componentdidMount() 根本没有触发。 甚至没有显示 console.logs。 为什么? 请帮忙。!

尝试通过以下方式修复代码:在您的父组件中:

const movies = [896, 895]

const cards = movies.map(movie => {
   <FlipCard number = 'movie' />
})

在您的子组件中

state = {
  poster: 'http://image.tmdb.org/t/p/w500',
}

componentDidMount() {
   axios.get(`https://api.themoviedb.org/3/movie/${this.props.number}api_key=*******&language=en-US`
.then(res=>{
    this.setState({poster: this.state.poster + res.data.poster_path})   
    console.log(this.props);             
})}  

您可以解决此问题并使用箭头函数和异步等待方法编写更好的代码

state = {
  poster: 'http://image.tmdb.org/t/p/w500',
}

componentDidMount() {
  getPoster()
} 

const getPoster = async () => {
  try {
    const response = await axios.get(`https://api.themoviedb.org/3/movie/${this.props.number}api_key=*******&language=en-US`)
    this.setState({poster: this.state.poster + response.data.poster_path})   
    console.log(this.props);             
  } catch(err) {
    console.log(err)
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM