簡體   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