React - How to force a function component to render?

前端 未结 7 519
眼角桃花
眼角桃花 2020-12-02 18:18

I have a function component, and I want to force it to re-render.

How can I do so?
Since there\'s no instance this, I cannot call this.forceU

7条回答
  •  孤城傲影
    2020-12-02 18:44

    Update react v16.8 (16 Feb 2019 realease)

    Since react 16.8 released with hooks, function components are now have the ability to hold persistent state. With that ability you can now mimic a forceUpdate:

    function App() {
      const [, updateState] = React.useState();
      const forceUpdate = React.useCallback(() => updateState({}), []);
      console.log("render");
      return (
        
    ); } const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);
    
    
    

    Note that this approach should be re-considered and in most cases when you need to force an update you probably doing something wrong.


    Before react 16.8.0

    No you can't, State-Less function components are just normal functions that returns jsx, you don't have any access to the React life cycle methods as you are not extending from the React.Component.

    Think of function-component as the render method part of the class components.

提交回复
热议问题