MST

星途 面试题库

面试题:React中componentDidMount在数据获取场景的应用

在React组件中,假设我们需要从后端API获取用户列表数据并展示。请用代码示例说明如何在componentDidMount生命周期方法中进行数据获取操作,并处理可能出现的异常。
34.5万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试
import React, { Component } from 'react';

class UserList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      users: [],
      error: null
    };
  }

  componentDidMount() {
    fetch('YOUR_API_URL')
    .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
    .then(data => {
        this.setState({ users: data });
      })
    .catch(error => {
        this.setState({ error: error.message });
      });
  }

  render() {
    const { users, error } = this.state;
    if (error) {
      return <div>Error: {error}</div>;
    }
    return (
      <div>
        <h1>User List</h1>
        <ul>
          {users.map(user => (
            <li key={user.id}>{user.name}</li>
          ))}
        </ul>
      </div>
    );
  }
}

export default UserList;