我的 ReactJS 应用程序在从 api 获取数据时遇到了问题。我仍然有一个错误:“无法读取未定义的属性‘地图’”,我不知道为什么会发生这种情况。
我的代码:UsersList.js
import React from 'react';
import ReactDOM from 'react-dom';
import fetch from 'isomorphic-fetch';
import { Card, Container, Icon } from 'semantic-ui-react'
import User from './User'
class ProfilesList extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [],
fetched: false,
loading: false,
};
}
componentWillMount(){
this.setState({
loading : true
});
fetch('http://58be98154389c312007f403f.mockapi.io/users/users').then(res => res.json())
.then(res =>{
this.setState({
users : res.results,
loading : true,
fetched : true
});
});
}
render() {
const {fetched, loading, users} = this.state;
let content;
if(fetched){
content = <div>{this.state.users.map((user,index) =>
<User key={user.username} id={index+1} user={user}/>)}</div>;
}
else if(loading && !fetched){
content = <p> Loading ...</p>;
}
else{
content = (<div></div>);
}
return (
<div>
{content}
</div>
);
}
}
export default ProfilesList;
User.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Card, Container, Icon } from 'semantic-ui-react'
class User extends React.Component {
render() {
const {user, id} = this.props;
return (
<Card
image='http://semantic-ui.com/images/avatar/large/elliot.jpg'
header={user.username}
meta='Friend'
description='Elliot is a sound engineer living in Nashville who enjoys playing guitar and hanging with his cat.'
extra={(
<a>
<Icon name='user' />
16 Friends
</a>
)}
/>
);
}
}
export default User;
谢谢你的帮助!
你state.users
当你尝试做的是未定义this.state.users.map()
在你的render
功能。所以任务#1 是找出为什么你fetch()
返回 undefined 并修复它。当您得到未定义的结果或其他错误并适当地设置您的状态时,对这种情况进行一些处理是一个好主意。此外,我倾向于undefined
在尝试之前检查预期的数组是否不是map
,如下所示:
{
expectedArray
?
expectedArray.map(someMappingFunction)
:
<div>expectedArray was 'undefined' or otherwise 'falsy'</div>
}
这样的条件语句称为“三元”并且非常有用,因为它可以作为“if/else”语句嵌入到 JSX 中。它的形式为(condition) ? (expression if true) : (expression if false)
。例如:
var foo = 7;
var bar = (foo % 2 == 0) ? "Even" : "Odd";
console.log(bar); // "Odd"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句