[英]Calling componentDidMount inside a class Component's function
In my react application, I have a courseslist and the user can Deactivate a course.在我的 React 应用程序中,我有一个课程列表,用户可以停用课程。
After deactivating I wanted to re-render my courselist
component to update the course status to "Inactive" from "Active" without using forceUpdate()
or this.setState()
as both didn't work and forceUpdate()
is not recommended too.停用后,我想重新呈现我的课程courselist
组件以将课程状态从“活动”更新为“非活动”,而不使用forceUpdate()
或this.setState()
因为两者都不起作用,也不推荐forceUpdate()
。
I am getting the course Info in my componentDidMount()
.我正在我的componentDidMount()
获取课程信息。
So after when the course status changes I called this.componentDidMount()
inside my updatedCourseStatus()
function and It's working.因此,当课程状态发生变化后,我在我的updatedCourseStatus()
函数中调用了this.componentDidMount()
并且它正在工作。
I just wanted to know if this approach have any bad effect on the application or any other approach to re-render the component better than this.我只是想知道这种方法是否对应用程序或任何其他方法比这更好地重新渲染组件有任何不良影响。
Here is my CourseList Component:这是我的 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){};
};
I want to use the data that I am getting from componentDidMount()
not from onDisableCourse()
;我想使用从componentDidMount()
而不是onDisableCourse()
获取的数据;
So I cannot do this.setState({courses: resData.updatedCourses})
;所以我不能这样做this.setState({courses: resData.updatedCourses})
;
我认为您应该使用componentDidUpdate()
函数而不是componentDidMount()
,因此您不必在onDisableCourse()
调用该函数。
this.setState
should work perfectly.If it ain't working , it means you might have inhereted PureComponent
instead of Component
, or returned false
in shouldComponentDidUpdate()
this.setState
应该可以完美运行。如果它不起作用,则意味着您可能继承了PureComponent
而不是Component
,或者在shouldComponentDidUpdate()
返回false
even then you may do something like this即使那样你也可以做这样的事情
fetchInfo = () => {
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){}
});
}
componentDidMount = () => {
this.fetchInfo()
}
onDisableCourse = id => {
this.fetchInfo()
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.