React - How to force a function component to render?

前端 未结 7 513
眼角桃花
眼角桃花 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:45

    The accepted answer is good. Just to make it easier to understand.

    Example component:

    export default function MyComponent(props) {
    
        const [updateView, setUpdateView] = useState(0);
    
        return (
            <>
                <span style={{ display: "none" }}>{updateView}</span>
            </>
        );
    }
    

    To force re-rendering call the code below:

    setUpdateView((updateView) => ++updateView);
    
    0 讨论(0)
提交回复
热议问题