繁体   English   中英

如何在ajax请求后使组件重新呈现

[英]How to cause the component to re-render after an ajax request

在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);
        });...

您可以执行两项操作来使同一组件呈现

首先:使用setState方法更新当前组件的状态。

除非shouldComponentUpdate()返回false,否则setState()将始终导致重新渲染。 如果正在使用可变对象,并且不能在shouldComponentUpdate()实现条件渲染逻辑,则仅当新状态不同于先前状态时调用setState()才能避免不必要的重新渲染。

其次:如果您不想更新当前组件的任何状态,则可以调用forceUpdate 您可以像this.forceUpdate()这样称呼它。

调用forceUpdate()将导致在组件上调用render( ),而跳过shouldComponentUpdate() 这将触发子组件的正常生命周期方法,包括每个子组件的shouldComponentUpdate()方法。 如果标记发生更改,React仍然只会更新DOM。

假设您正在执行一个异步请求并从中获取响应,那么您将希望使用所获取的数据来更新组件的状态,因此setState将是您前进的方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM