繁体   English   中英

状态更改后,React不会重新呈现虚拟DOM

[英]React doesn't re-render the Virtual DOM after the state is changed

我有一个从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));  
  }
}

我相信您不是在更新状态,而是像这样更新状态

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

我的猜测是您的获取响应是一个数组,而不是一个对象。

这意味着您将拥有一个状态对象,该对象的属性为0、1,2等(如任何数组),而不是“课程”。

尝试将您的回答映射到courses属性:

.then(response => this.setState({courses: response}))

暂无
暂无

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

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