简体   繁体   English

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

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

I have a component that loads courses from RESTful API. 我有一个从RESTful API加载课程的组件。 After the courses have been loaded state is changed and the component should render CourseCard components with the loaded data. 加载课程后,状态将更改,组件应使用已加载的数据呈现CourseCard组件。

The problem is that when loadCourses() method changes the state of the component no CourseCard is displayed 问题是当loadCourses()方法更改组件的状态时,不会显示CourseCard

This is code of the component: 这是组件的代码:

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));  
  }
}

I believe you are not updating state, update the state like this 我相信您不是在更新状态,而是像这样更新状态

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

My guess would be that your fetch response is an array, not an object. 我的猜测是您的获取响应是一个数组,而不是一个对象。

Which means you will have a state object with properties 0,1,2 etc (like any array) instead of 'courses'. 这意味着您将拥有一个状态对象,该对象的属性为0、1,2等(如任何数组),而不是“课程”。

try to map your response to the courses attribute: 尝试将您的回答映射到courses属性:

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

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

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