【问题标题】:React doesn't re-render the Virtual DOM after the state is changed状态改变后 React 不会重新渲染虚拟 DOM
【发布时间】:2018-09-04 13:05:56
【问题描述】:

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

【问题讨论】:

  • 永远不要直接在渲染中进行绑定,而是始终在构造函数中进行绑定或使用箭头函数
  • @Think-Twice 箭头函数在渲染中具有相同的陷阱绑定(在每个渲染上创建一个新函数)
  • @Nick Zuber 同意,但并非总是如此。在某些情况下,箭头函数也只呈现一次。检查此线程stackoverflow.com/questions/52031147/…
  • @Think-Twice 也许我们互相误解了——渲染方法中的箭头函数会在每次渲染时创建一个新函数。检查文档reactjs.org/docs/faq-functions.html 在类级别上定义的箭头函数可以解决问题(只渲染一次并绑定范围)????
  • 是的,在类级别上它只呈现一次。

标签: javascript reactjs


【解决方案1】:

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

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

【讨论】:

  • 你不知道JSON的结构。
  • 因为他使用地图我相信它的数组类型。
  • 我相信 axios 会将 JSON 响应附加到 data 属性。获取没有。只是给 OP 的注释。
【解决方案2】:

我猜你的 fetch 响应是一个数组,而不是一个对象。

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

尝试将您的响应映​​射到courses 属性:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-22
    • 2020-09-10
    • 2020-01-20
    • 2020-06-26
    • 1970-01-01
    • 2021-06-25
    • 2018-12-31
    • 1970-01-01
    相关资源
    最近更新 更多