简体   繁体   English

react-native fetch api数组

[英]react-native fetch api arrays

I am trying to fetch facebook movie data using axios. 我正在尝试使用axios获取Facebook电影数据 In my console, I see the fetched data, but I have trouble getting when I want to access the title text. 在我的控制台中,我看到了获取的数据,但是当我想访问标题文本时,我无法获取。

 class BoardScreen extends Component {

      constructor(props) {
         super(props);
         this.state = { movies: [] };
      }

        componentWillMount() {
          axios.get('https://facebook.github.io/react-native/movies.json')
            .then(response => this.setState({ movies: response.data }));
        }

renderMovies() {
return this.state.movies.movies.map(movies => <Text>{movies.title}</Text>)
}

      render() {
if(this.state.movies.length === 0) {
     return null;
   }
        console.log(this.state.movies.title, 'movies')

        return (
          <View>
          {this.renderMovies()}
          </View>
                )
              }
            }

The code above only will give me the main title text The Basics - Networking What I really want is to access to each movie title and display. 上面的代码只会给我主要标题文本The Basics - Networking我真正想要的是访问每个电影标题和显示。

How could I fetch each array title? 我怎么能获取每个数组标题?

What you need is this looping through it and bind the data. 你需要的是循环它并绑定数据。

this.state.movies.movies.map(a=>{
           return <div key={a.id}>{a.title}</div>
        })       

Ofcourse you need to check if movies is not null, so render should look like this 当然,您需要检查电影是否为空,因此渲染应该如下所示

  render() {

    if(this.state.movies.length === 0) {
      return null;
    }
    console.log(this.state.movies.movies, 'movies');

    return (
        this.state.movies.movies.map(a=>{
           return <div key={a.id}>{a.title}</div>
        })       

    )
  }

Demo 演示

IMO, would be be very very easy if you just have looked here IMO,如果你只是看过这里 ,那将是非常容易的

add return statement in renderMovie() method. 在renderMovie()方法中添加return语句。

renderMovie() {
  return this.state.movies.movies.map(movies => {
 return <Text>{movies.title}</Text>
})
}
class BoardScreen extends Component {

    constructor(props) {
        super(props);
        this.state = { movies: [] };
    }

    componentWillMount() {
        axios.get('https://facebook.github.io/react-native/movies.json')
        .then(response => this.setState({ movies: response.data }));
    }

    render() {
        return (
            <View>
                this.state.movies.movies.map((movie) =>
                    < Text key={movies.id}>
                        {movie.title}
                    </Text>
                );
            </View>
        )
    }
}

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

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