首页 > 解决方案 > 如何修复 Reactjs 中的“items.map 未定义”错误

问题描述

我只是关于 reactjs 的新开发人员

我正在尝试映射数据。我正在关注 reactjs 教程,这是我的结果,但我尝试并再次尝试它是否不起作用。我该如何解决??

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }
  componentDidMount() {
 // API from reqres
    fetch("https://reqres.in/api/users/2")
      .then(res => res.json())
      .then(
        (result) => {
          console.log(result.data);
          this.setState({
            isLoaded: true,
            items: result.data
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }
  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div>
//this is the problem
          {items.map(item=> { 
            return <div>
              <p>{item.id}</p>
            </div>
          })}
        </div>
      );
    }
  }
}

export default App;

请帮助我,我只想查看我的数据:(

在我将 fetch 更改为 Axios 后,我遇到了同样的问题??

    Axios({
      method:"GET",
      url:"https://reqres.in/api/users"
    }).then(res => {
      this.setState({
         isLoaded:true,
           items: res.data
      })
      console.log(res.data)

  }).catch(err => {
      console.log(err)

  })

标签: reactjs

解决方案


您可以通过为项目提供默认值来解决此问题:

const { error, isLoaded, items = [] } = this.state;

推荐阅读