嘿,伙计们,我已经设法让我的星球大战api数据从json显示在我的应用程序上。我通过将状态设置为people.name来获得name对象,但是当我将其设置为“people”时,它会呈现所有内容,包括我不想使用的数据。
class Card extends Component {
constructor(){
super()
this.state = {
jedi: [],
searchfield: ''
}
}
componentDidMount(){
fetch('https://swapi.co/api/people/1')
.then(response => { return response.json()})
.then(people => this.setState({jedi: JSON.stringify(people)}))
}
render(){
return (
<div className = 'charcards'>
<div>
<img className= 'pic' alt = 'Luke Skywalker' src = {luke} />
</div>
<hr/>
<h2 className = "name1"> Name: {this.state.jedi.name}</h2>
<h2 className = 'height'> {this.state.jedi.height}</h2>
</div>
);
}
}
如果我把.then(people => this.setState({jedi: JSON.stringify(people)}))
改成
.then(people => this.setState({jedi: JSON.stringify(people.name)}))
但是我无法调用我的其他数据,比如高度、质量等。当我只是调用人们时,它调用了大量不必要的数据。如果我循环遍历api并挑选出我想要的数据,那么当我尝试遍历它但无法呈现数据时,我该如何处理呢?调用this.state.jedi.name
或this.state.jedi.height
并不起作用,因为它只是调用所有内容
发布于 2018-06-08 08:31:58
在API支持之前,您不能获取部分数据。例如,你总是可以只使用你想要的。找到有用的源码...
class Card extends Component {
constructor(){
super()
this.state = {
jediBio: {},
searchfield: ''
}
}
componentDidMount(){
fetch('https://swapi.co/api/people/1')
.then(response => { return response.json()})
.then(people => this.setState({jediBio: people}))
}
render(){
//Define luke here else will throw luke as undefined
Let luke = "http://media.comicbook.com/2017/03/star-wars-luke-skywalker-239385.png";
return (
<div className = 'charcards'>
<div>
<img className= 'pic' alt = 'Luke Skywalker' src = {luke} />
</div>
<hr/>
<h2 className = "name1"> Name: {this.state.jediBio.name}</h2>
<h2 className = 'height'> {this.state.jediBio.height}</h2>
</div>
);
}
}
发布于 2018-06-08 08:00:11
我认为问题出在下面这一行:
.then(people => this.setState({jedi: JSON.stringify(people)})
您正在对response对象调用JSON.stringify()
,它会将其序列化为一个字符串。如果您希望能够访问响应JSON的属性,您可以删除它以获取:
.then(people => this.setState({jedi: people})
而且,您的this.state.jedi
状态看起来是一个数组,因此在检索name
和height
属性时,要确保遍历每个this.state.jedi
,而不是执行this.state.jedi.<name | height>
。
https://stackoverflow.com/questions/50751453
复制相似问题