简体   繁体   English

得到这个类型错误:无法读取未定义的属性“地图”

[英]getting this TypeError: Cannot read property 'map' of undefined

I'm working on a react.js app to search and display GitHub users.我正在开发一个 react.js 应用程序来搜索和显示 GitHub 用户。 I'm getting the above message when I try and display the users.当我尝试显示用户时,我收到了上述消息。 Any tips on how I get around this?关于我如何解决这个问题的任何提示?

import React, { useContext } from 'react';
import UserItem from './UserItem';
import Spinner from '../layout/Spinner';
import GithubContext from '../../context/github/githubContext';

const Users = () => {
  const githubContext = useContext(GithubContext);

  const { loading, users } = githubContext;

  if (loading) {
    return <Spinner />;
  } else {
    return (
      <div style={userStyle}>
        {users.map(user => (
          <UserItem key={user.id} user={user} />
        ))}
      </div>
    );
  }
};

const userStyle = {
  display: 'grid',
  gridTemplateColumns: 'repeat(3, 1fr)',
  gridGap: '1rem'
};

export default Users;

The array hasn't been created by the time you call the map function - you can make the map function conditional on the array existing so it won't call unless it's ready. The array hasn't been created by the time you call the map function - you can make the map function conditional on the array existing so it won't call unless it's ready.

You can use optional chaining for this purposes, in this case you will not have error, and when users become an array all users will be rendered.您可以为此目的使用可选链接,在这种情况下您不会出错,并且当用户成为数组时,所有用户都将被呈现。 eg例如

import React, { useContext } from 'react';
import UserItem from './UserItem';
import Spinner from '../layout/Spinner';
import GithubContext from '../../context/github/githubContext';

const Users = () => {
  const githubContext = useContext(GithubContext);

  const { loading, users } = githubContext;

  if (loading) {
    return <Spinner />;
  } else {
    return (
      <div style={userStyle}>
        {users?.map(user => (
          <UserItem key={user.id} user={user} />
        ))}
      </div>
    );
  }
};

const userStyle = {
  display: 'grid',
  gridTemplateColumns: 'repeat(3, 1fr)',
  gridGap: '1rem'
};

export default Users;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM