我正在尝试使用axios获取Facebook电影数据。在我的控制台中,我看到了获取的数据,但是当我想要访问标题文本时,我无法获得。
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 Basics - Networking
我真正想要的是访问每个电影标题和显示。
如何获取每个数组标题?
你需要的是遍历它并绑定数据。
this.state.movies.movies.map(a=>{
return <div key={a.id}>{a.title}</div>
})
当然,您需要检查电影是否为空,因此渲染应如下所示
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>
})
)
}
演示
IMO,如果你只是看这里,会非常非常容易
在 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>
)
}
}