javascript - 状态改变后 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));
}
}
解决方案
我相信你没有更新状态,像这样更新状态
fetch(url)
.then((response) => response.json())
.then((response) => this.setState({courses : response.data});
推荐阅读
- wordpress - 如何将 __block_editor_compatible_meta_box 参数设置为 false?
- java - 错误:无法启动守护进程。此问题可能是由于守护程序配置不正确造成的
- eclipse - 在 Eclipse 中更改控制台大小
- php - 使用 REST API 的自动完成功能在本地工作,但不能在 Web 服务器上工作
- c - 零填充字符串到有限长度
- python - 如何在图像识别模型中上传新文件
- couchbase - 如何获取 couchbase 中的文档列表,我们必须根据属性过滤另一个数组中的数组?
- excel - 对于给定工作簿的给定工作表,根据其名称上的条件删除该工作表中的所有命名范围
- websocket - Socket IO 监听器在 Android 中不起作用
- scala - 为什么在写入 Hive 表期间 Spark 数据框中的时间戳列发生了变化?