0

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

1 回答 1

3

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

第一:使用方法更新当前组件的状态setState

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

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

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

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

于 2017-11-17T10:09:16.970 回答