无法阅读财产' map'在ReactJS中未定义

时间:2017-03-07 13:31:50

标签: reactjs reactive-programming

我的ReactJS应用程序遇到了从api获取数据的问题。我仍然有一个错误:'无法读取属性' map'未定义的,我不知道它为什么会发生。

我的代码: 的 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;

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

当您尝试在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"