我需要从这个电影阵列的第一个位置获取String
仅在第一个位置上标题为“星球大战”
但我的代码却返回null
{
title: "The Basics - Networking",
description: "Your app fetched this from a remote endpoint!",
movies: [
{
title: "Star Wars",
releaseYear: "1977"
},
{
title: "Back to the Future",
releaseYear: "1985"
},
{
title: "The Matrix",
releaseYear: "1999"
},
{
title: "Inception",
releaseYear: "2010"
},
{
title: "Interstellar",
releaseYear: "2014"
}
]
}
constructor(props){
super(props)
this.state = {
xName: '',
};
}
componentDidMount() {
fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) =>
{this.setState({xName: responseJson.title[0]});})
.catch((error) => {
console.error(error);
})
alert(this.state.xName);
}
但是我的警报返回xName的null。它不能从标题设置状态
答案 0 :(得分:1)
我会这样做
class movieFetch extends Component{
constructor(props){
super(props);
this.state = {movies: ''};
}
componentDidMount() {
fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {this.setState({movies: responseJson.title});})
.catch((error) => {
console.error(error);
})
}
render(){
return (
alert({this.state.movies[0].title}),
<h3>{this.state.movies[0].title}</h3>
);
}
答案 1 :(得分:0)
要获得星球大战冠军,您需要获得responseJson.movies[0].title
而不是responseJson.title[0]