gpt4 book ai didi

javascript - 在 ReactJS 中将 json 结果推送到数组的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-03 02:50:12 25 4
gpt4 key购买 nike

我想获取 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')
);

但是我在控制台中出现以下错误:

TypeError: j.results[i] is undefined

如何修复此错误?

最佳答案

我不确定这是解决此问题的 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 。希望这是有道理的。

关于javascript - 在 ReactJS 中将 json 结果推送到数组的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47902296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com