首页 > 解决方案 > 状态改变后 React 不会重新渲染虚拟 DOM

问题描述

我有一个从 RESTful API 加载课程的组件。课程加载后,状态发生更改,组件应CourseCard使用加载的数据呈现组件。

问题是当loadCourses()方法更改组件的状态时,不会CourseCard显示

这是组件的代码:

class Courses extends Component {

  constructor() {
    super();

    this.state = {
      courses: []
    };
  }

  componentDidMount() {
    this.loadCourses(null);
  }

  render() {
    return (
      <div>
        <CourseCategoriesBar loadCourses={this.loadCourses.bind(this)} />

        <div style={{
          paddingBottom: "120px",
          marginBottom: "30px",
        }}>
          <div className="container">
            <div className="row">

              {this.state.courses.map((course, i) => {
                return (
                  <div className="col-lg-3 col-md-6 col-sm-12" key={i}>
                    <CourseCard type="e" key={i}/>
                  </div>
                );
              })}

            </div>
          </div>
        </div>
      </div>
    );
  }

  loadCourses(id) {
    if (!id) id = ""
    let url = "http://localhost:8000/api/courses/category/" + id;

    fetch(url)
      .then((response) => response.json())
      .then((response) => this.setState(response));  
  }
}

标签: javascriptreactjs

解决方案


我相信你没有更新状态,像这样更新状态

fetch(url)
  .then((response) => response.json())
  .then((response) => this.setState({courses : response.data});  

推荐阅读