考虑下面的钩子示例

   import { useState } from 'react';

   function Example() {
       const [count, setCount] = useState(0);

       return (
           <div>
               <p>You clicked {count} times</p>
               <button onClick={() => setCount(count + 1)}>
                  Click me
               </button>
          </div>
        );
     }

基本上,我们使用this.forceUpdate()方法强制组件立即在React类组件中重新渲染,如下例所示

    class Test extends Component{
        constructor(props){
             super(props);
             this.state = {
                 count:0,
                 count2: 100
             }
             this.setCount = this.setCount.bind(this);//how can I do this with hooks in functional component 
        }
        setCount(){
              let count = this.state.count;
                   count = count+1;
              let count2 = this.state.count2;
                   count2 = count2+1;
              this.setState({count});
              this.forceUpdate();
              //before below setState the component will re-render immediately when this.forceUpdate() is called
              this.setState({count2: count
        }

        render(){
              return (<div>
                   <span>Count: {this.state.count}></span>. 
                   <button onClick={this.setCount}></button>
                 </div>
        }
 }

但我的问题是,我如何才能强制上述功能组件重新渲染立即与挂钩?


当前回答

在Hook中有许多强制重渲染的方法。

对我来说,使用useState()和引用对象值提示的简单方法。

const [, forceRender] = useState({});

// Anywhre
forceRender({});

Codesandbox例子

其他回答

const useForceRender = () => {
  const [, forceRender] = useReducer(x => !x, true)
  return forceRender
}

使用

function Component () {
  const forceRender = useForceRender() 
  useEffect(() => {
    // ...
    forceRender()
  }, [])

我对forceUpdate的变化不是通过计数器,而是通过一个对象:

// Emulates `forceUpdate()`
const [unusedState, setUnusedState] = useState()
const forceUpdate = useCallback(() => setUnusedState({}), [])

因为{}!=={}每次。

有点晚了,但我注意到大多数(所有)的答案都错过了可以传递回调到forceUpdate生命周期方法的部分。

根据react源代码,此回调具有与setState方法中的行为相同的行为-它在更新后执行。

因此,最正确的实现应该是这样的:

/** *增加导致重传并执行回调的状态 * @param {function}回调-状态更新后执行的回调 * @返回{函数} * / export const useForceUpdate = (callback) => { const [state, updater] = useReducer((x) => x + 1,0); useEffect(() => { Callback && Callback (); },[状态]); 返回useCallback(() => { 更新(); },[]); };

@MinhKha的回答:

使用useReducer可以更简洁:

const [, forceUpdate] = useReducer(x => x + 1, 0);

用法: forceUpdate() -没有参数的清洁器

简单的代码

const forceUpdate = React.useReducer(bool => !bool)[1];

Use:

forceUpdate();