从API提取和映射反应显示数据

时间:2019-03-04 01:43:19

标签: reactjs dictionary

我正在尝试通过制作电影网络应用程序来学习React。我试图从电影API中提取即将上映的电影,并从中显示信息,但是我不断收到错误消息:

  

第37行:希望进​​行赋值或函数调用,而是看到了   表达式no-unused-expressions

请原谅我不是太熟悉此框架,也不是JS专业人士。这是我的代码:

    export default class Upcoming extends Component {

    state = {
        upcomingMovies: []
      }

      fetchUpcoming() {
          fetch(`https://api.themoviedb.org/3/movie/upcoming?api_key=${API_KEY}&language=en-US&page=1`)
              // We get the API response and receive data in JSON format...
              .then(response => response.json())
              // ...then we update upcomingMovies State
              .then(data =>
                  this.setState({
                      upcomingMovies: data.results
                  })
              )
    }

    componentDidMount(){
        this.fetchUpcoming();
    }

  render() {

    return(
        <Container>
            { this.state.upcomingMovies.map((upcomingMovie) => {
                console.log(upcomingMovie);
                const title = upcomingMovie.title;
                console.log(title);
                <h1>{title}</h1>
            })}

        </Container>
    )

  }

}

3 个答案:

答案 0 :(得分:0)

您在map函数的最后一行中缺少return语句。应该是return <h1>{title}</h1>

答案 1 :(得分:0)

Map函数应该返回一些东西来生成ui。

    export default class Upcoming extends Component {

    state = {
        upcomingMovies: []
      }

      fetchUpcoming() {
          fetch(`https://api.themoviedb.org/3/movie/upcoming?api_key=${API_KEY}&language=en-US&page=1`)
              // We get the API response and receive data in JSON format...
              .then(response => response.json())
              // ...then we update upcomingMovies State
              .then(data =>
                  this.setState({
                      upcomingMovies: data.results
                  })
              )
    }

    componentDidMount(){
        this.fetchUpcoming();
    }

  render() {

    return(
        <Container>
            { this.state.upcomingMovies.map((upcomingMovie) => (
               <h1>{title}</h1>
            ))}
        </Container>
    )

  }

}

答案 2 :(得分:0)

您应该使用箭头功能写fetchUpcoming。因此,可以在this.setState()函数范围内使用fetchUpcoming方法。例如:

const fetchUpcoming = async() {
  try {
    let response = await fetch(
      `https://api.themoviedb.org/3/movie/upcoming?api_key=${API_KEY}&language=en-US&page=1`,
    );
    let responseJson = await response.json();
    return this.setState({
                      upcomingMovies: responseJson.data.results
                  })
  } catch (error) {
    console.error(error);
  }
}