ReactJS:setState之后状态为空,然后设置值
我试着做一个简单的水疗只是为了学习。我正在尝试使用RiotAPI(developer.riotgames.com),但我不工作 这是我的密码:ReactJS:setState之后状态为空,然后设置值,reactjs,fetch,array.prototype.map,Reactjs,Fetch,Array.prototype.map,我试着做一个简单的水疗只是为了学习。我正在尝试使用RiotAPI(developer.riotgames.com),但我不工作 这是我的密码: import React, { Component } from 'react'; import './App.css'; import Header from './components/Header'; class App extends Component { constructor() { super(); this.st
import React, { Component } from 'react';
import './App.css';
import Header from './components/Header';
class App extends Component {
constructor() {
super();
this.state = {
riotAPIdata: []
}
}
componentWillMount() {
fetch('https://global.api.riotgames.com/api/lol/static-data/BR/v1.2/champion?champData=image%2Cinfo%2Cstats%2Ctags&dataById=false&locale=pt_BR&api_key=RGAPI-0ed56255-77e0-4002-8e44-024f74be8249')
.then(response => response.json())
.then(riotAPI => { this.setState({ riotAPIdata: riotAPI.data }) })
}
render() {
if (this.state.riotAPIdata !== {}) {
console.log(this.state.riotAPIdata)
} else {
console.log("Carregando")
}
return (
<div className="App">
<Header />
<div className="App-intro">
{this.state.riotAPIdata.map((obj, i) => {
return <p key={i}>{obj.name}</p>
})}
</div>
</div>
);
}
}
export default App;
import React,{Component}来自'React';
导入“/App.css”;
从“./components/Header”导入标题;
类应用程序扩展组件{
构造函数(){
超级();
此.state={
riotAPIdata:[]
}
}
组件willmount(){
取('https://global.api.riotgames.com/api/lol/static-data/BR/v1.2/champion?champData=image%2Cinfo%2Cstats%2Ctags&dataById=false&locale=pt_BR&api_key=RGAPI-0ed56255-77e0-4002-8e44-024f74be8249')
.then(response=>response.json())
.then(riotAPI=>{this.setState({riotAPIdata:riotAPI.data})})
}
render(){
if(this.state.riotAPIdata!=={}){
console.log(this.state.riotAPIdata)
}否则{
控制台日志(“Carregando”)
}
返回(
{this.state.riotAPIdata.map((obj,i)=>{
返回{obj.name}
})}
);
}
}
导出默认应用程序;
控制台显示以下错误:
首先,它记录两次同一行,然后映射不起作用!有什么帮助吗?费利克斯·克林(Felix Kling)在评论中所说的完全正确,我过去使用过类似的东西,我能够使用map,也许它可以帮助你,在你的“组件Willmount”中尝试类似的东西
var response_json = response.json
this.setState({riotAPIdata: response_json.data.map((val) => {
return {
val: val
};
)})
然后你可以在你的渲染方法中使用这样的值
{this.state.riotAPIdata.map((obj, i) => {
return <p key={i}>{obj.val.name}</p>
})}
{this.state.riotAPIdata.map((obj,i)=>{
返回{obj.val.name}
})}
就像我不确定riotAPIdata的结构一样,但如果能好好利用它,它肯定会起作用的
希望这有帮助 第二个日志清楚地表明,
riotAPIdata
是一个对象,而不是数组。对象没有.map
方法。换句话说,riotAPI.data
不是数组。解决方案是:在更新状态之前将对象转换为数组,或者找到不同的方法遍历数据结构。FWIW,this.state.riotAPIdata!=={}
将始终为true
,因为对象是通过引用进行比较的。谢谢!!!成功了!:)酷,那么你可以标记我的答案以备将来参考:)