如何使用API在React中渲染列表
渲染从虚拟API获取的列表。
代码
app.js
import logo from './logo.svg';
import Header from './components/Header';
import MapArea from './components/MapArea';
import Card from './components/Card';
import './App.css';
import React from "react";
class App extends React.Component {
constructor(e){
super();
this.state = {
menu:false,
userData:[]
}
}
componentDidMount() {
fetch("https://reqres.in/api/users?page=2")
.then((a)=>{return a.json()})
.then((b)=>{
this.setState({
userData:b
})
})
}
card.js
function Card(props){
let userData = props.data.userData.data;
console.log(userData) //Sometimes WORKING FINE
return(<div>{userData.map((item)=>{<h1 key={item.id}>item.id</h1>})}</div>)
}
export default Card;
问题
是有时是控制台。log有效,有时没有。然后,我必须在card.js的渲染方法中删除JavaScript“ {}”,然后再保存并再次粘贴并保存。当Console.log无法正常工作时,我还添加了控制台的图像
。
To render the list fetched from dummy API.
The Code
App.js
import logo from './logo.svg';
import Header from './components/Header';
import MapArea from './components/MapArea';
import Card from './components/Card';
import './App.css';
import React from "react";
class App extends React.Component {
constructor(e){
super();
this.state = {
menu:false,
userData:[]
}
}
componentDidMount() {
fetch("https://reqres.in/api/users?page=2")
.then((a)=>{return a.json()})
.then((b)=>{
this.setState({
userData:b
})
})
}
Card.js
function Card(props){
let userData = props.data.userData.data;
console.log(userData) //Sometimes WORKING FINE
return(<div>{userData.map((item)=>{<h1 key={item.id}>item.id</h1>})}</div>)
}
export default Card;
The Problem
Now the thing is that sometimes the console.log works and sometimes it doesnt. Then I have to remove the javascript "{}" in render method of the Card.js and save and again paste it back and save. I have also added image of console when the console.log doesnt work
Also the list doesnt render.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的初始状态是错误的。虚拟API返回“数据”字段下的数组,因此您需要在初始状态下匹配该结构。
Your initial state is wrong. The dummy api returns the array under the "data" field, so you need to match that structure in the initial state.
.map()
的回调没有返回任何内容。箭头功能仅在函数周围没有卷发括号时具有隐式返回。因此,要么卸下卷发括号:或添加明确的返回:
The callback for
.map()
isn't returning anything. Arrow functions only have an implicit return if there are no curly braces surrounding the function. So either remove the curly braces:or add an explicit return:
@kalpeshshende您的console.log是“不起作用的”,因为您的初始状态与从API返回的JSON没有相同的结构。我建议更改您的componentDidmount
和内部组件:
let userData = props.data.userdata;
>或
const {userdata} = props.data;
@kalpeshshende your console.log is "not working" because your initial state doesn't have the same structure as the json returned from the API. I recommend changing your componentDidMount
and the inside the component:
let userData = props.data.userData;
or
const {userData} = props.data;