【发布时间】:2020-03-07 06:28:30
【问题描述】:
在我的反应应用程序中,我有一个课程列表,用户可以停用课程。
停用后,我想重新渲染 mycourselist 组件,以在不使用 forceUpdate() 或 this.setState() 的情况下将课程状态从“活动”更新为“非活动”,因为两者都不起作用而 forceUpdate() 不是也推荐。
我在componentDidMount() 中获取课程信息。
因此,当课程状态发生变化后,我在 updatedCourseStatus() 函数中调用了 this.componentDidMount() 并且它正在工作。
我只是想知道这种方法是否对应用程序有任何不良影响,或者是否有任何其他方法可以比这更好地重新渲染组件。
这是我的 CourseList 组件:
state = {
pageLoading: true,
courses: '',
totalCourses: 0
};
componentDidMount() {
fetch('url')
.then(res => {
if (!res.ok) throw res;
return res.json();
})
.then(resData => {
this.setState({
courses: resData.courses,
totalCourses: resData.totalCourses,
pageLoading: false
});
})
.catch(err){}
});
}
onDisableCourse = id => {
fetch(url)
.then(res => {
if (!res.ok) throw res;
return res.json();
})
.then(resData => {
console.log(resData);
this.componentDidMount();
})
.catch(err){};
};
我想使用从componentDidMount() 而不是onDisableCourse() 获得的数据;
所以我不能this.setState({courses: resData.updatedCourses});
【问题讨论】:
-
setState 不起作用是什么意思?您是否尝试直接更新阵列?因为它不会起作用。您需要使用 array.map 函数生成一个新数组并将其传递给 setState。
-
这就是我不想做的。我从 resData 得到的不包含我想要更新的数据,因为它没有被填充,并且我在 componentDidMount 中得到填充的数据。我可以在我的服务器中的 resData 中实现填充,但我不想这样做。所以 resData 中的 setState() 不会有我需要的所有必需数据。
-
我也用了 this.setState(this.state) 也没用。
-
手动调用componentDidMount不是个好主意。相反,您可以编写另一个函数并在 componentDidMount 和其他您想要的地方调用它。这种方法会更整洁。
-
可以使用单独的函数来调用componentDidMount。但是为什么手动componentDidMount不好呢?
标签: javascript reactjs jsx