在ReactJs中的一个函数内重新渲染相同的组件。我正在添加评论,之后我想重新渲染相同的组件。有人可以帮忙吗?
commentPost() {...
axios.defaults.headers.common['Authorization'] = getToken;
axios.post(apiBaseUrl+'v1/comments/post-comment',input)
.then(function (response) {
console.log("Comment Post",response);
//here I want to rerender this component itself
})
.catch(function (error) {
console.log(error);
});...
答案 0 :(得分:3)
有两件事可以让同一个组件呈现
首先:使用setState
方法更新当前组件的状态。
setState()
将始终导致重新渲染,除非shouldComponentUpdate()
返回false。如果是可变对象 使用和条件渲染逻辑无法实现shouldComponentUpdate()
,仅在新版本时调用setState()
状态与以前的状态不同,将避免不必要的 重新呈现。
第二:如果您不想更新当前组件的任何状态,可以调用forceUpdate
。您可以将其称为this.forceUpdate()
。
调用
forceUpdate()
将导致render(
}被调用 组件,跳过shouldComponentUpdate()
。这将触发 子组件的正常生命周期方法,包括 每个孩子的shouldComponentUpdate()
方法。 React仍然只会 如果标记发生更改,则更新DOM。
假设您正在执行异步请求,您将从中获取响应,您希望使用您获得的数据更新组件的状态,因此setState
将成为您的前进方向