简体   繁体   中英

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

The following is my parent component:

const movies = [896, 895]

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

In the child component I am trying to access the props.number, but I am getting an error. The code of child component:

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

In browser, I am getting this error: enter image description here [Unexpected keyword 'this' at this.props.number]

In VS Code, I am getting this error enter image description here [ ':' expected at that axios line]

How can I resolve this issue?

EDIT : I did remove the curly braces. Now componentdidMount() is not firing at all. Even the console.logs are not being shown. Why? Please help.!

Try to fix the code in the following way: In your parent component:

const movies = [896, 895]

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

In your child component

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

You can fix this issue and write better code using arrow functions and async await method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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