【问题标题】:How to cause the component to re-render after an ajax requestajax请求后如何使组件重新渲染
【发布时间】:2018-05-01 01:48:04
【问题描述】:

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

【问题讨论】:

  • React 在其状态发生变化时触发组件重新渲染。您需要更新组件的状态,因此值得重新渲染它以显示更新的状态。
  • 您需要设置状态以使响应重新渲染。

标签: javascript reactjs rerender react-lifecycle


【解决方案1】:

你可以做两件事来渲染同一个组件

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

setState() 总是会导致重新渲染,除非 shouldComponentUpdate() 返回错误。如果可变对象正在 使用和条件渲染逻辑无法实现 shouldComponentUpdate(),只有当新的时候才调用setState() 状态不同于前一个状态将避免不必要的 重新渲染。

第二:如果您不想更新当前组件的任何状态,可以调用forceUpdate。您可以将其称为this.forceUpdate()

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

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

【讨论】:

  • forceUpdate怎么写?像这样:component.forceUpdate(callback)
  • this.forceUpdate() 是调用 forceUpdate 的方式
  • 我收到此错误:“无法读取未定义的属性 'forceUpdate'”
  • 我必须为我的所有字段做 setState ??
  • 什么意思,为所有字段设置状态
猜你喜欢
  • 2015-05-24
  • 2021-07-19
  • 2011-05-08
  • 2018-10-09
  • 2019-04-18
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 2020-01-12
相关资源
最近更新 更多