我想获取一个json api并将该结果推送到一个数组中:
import React from 'react';
import ReactDOM from 'react-dom';
function Users(){
const url = 'https://randomuser.me/api/?results=5';
let nodes = [];
fetch(url)
.then(response => {
return response.json();
})
.then(j => {
for( var i = 0; i <= j.results.length; i++ ){
nodes.push(<li>{j.results[i].name.first}</li>);
}
});
return(
<ul>{nodes}</ul>
);
}
ReactDOM.render(
<Users />,
document.getElementById('main')
);
&#13;
但是我在控制台中出现以下错误:
TypeError:j.results [i]未定义
如何解决此错误?
答案 0 :(得分:1)
我不确定这是解决此问题的react
方法。以下是您的问题的解决方案:
class Hello extends React.Component {
constructor(props){
super(props);
this.state = {
nodes: []
}
}
componentDidMount(){
this.fetchData();
}
fetchData(){
console.log('here')
const url = 'https://randomuser.me/api/?results=5';
fetch(url)
.then(response => response.json())
.then(data => {
const nodes = data.results;
this.setState({nodes})
})
}
render(){
return (
<ul>
{this.state.nodes.map(node => <li key={node.name.first} >{node.name.first}</li>)}
</ul>
)
}
}
工作示例here。希望它有意义。
答案 1 :(得分:0)
import React from 'react';
import ReactDOM from 'react-dom';
class Users extends React.Component{
constructor(props) {
super(props)
this.state = {
nodes: []
}
this.load()
}
load() {
const url = 'https://randomuser.me/api/?results=5';
return fetch(url)
.then(response => response.json())
.then(({results:nodes}) => this.setState({nodes}))
}
render() {
let {nodes} = this.state
return <ul>{nodes.map(({name:{first}}) => <li>{first}</li>)}</ul>
}
}
ReactDOM.render(
<Users />,
document.getElementById('main')
);