考虑下面的钩子示例

   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>
        }
 }

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


当前回答

一句话解决方案:

useState()[1];

useState返回一对值:当前状态和更新状态的函数——state和setter,这里我们只使用setter来强制重新呈现。

其他回答

我对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(() => { 更新(); },[]); };

这将渲染依赖组件3次(具有相等元素的数组是不相等的):

const [msg, setMsg] = useState([""])

setMsg(["test"])
setMsg(["test"])
setMsg(["test"])

你可以(ab)利用React在JSX代码中不打印布尔值的事实,使用普通钩子强制渲染

// create a hook
const [forceRerender, setForceRerender] = React.useState(true);

// ...put this line where you want to force a rerender
setForceRerender(!forceRerender);

// ...make sure that {forceRerender} is "visible" in your js code
// ({forceRerender} will not actually be visible since booleans are
// not printed, but updating its value will nonetheless force a
// rerender)
return (
  <div>{forceRerender}</div>
)

正如其他人提到的,useState工作-这是mobx-react-lite如何实现更新-你可以做一些类似的事情。

定义一个新的钩子useForceUpdate -

import { useState, useCallback } from 'react'

export function useForceUpdate() {
  const [, setTick] = useState(0);
  const update = useCallback(() => {
    setTick(tick => tick + 1);
  }, [])
  return update;
}

并将其用于组件-

const forceUpdate = useForceUpdate();
if (...) {
  forceUpdate(); // force re-render
}

参见https://github.com/mobxjs/mobx-react-lite/blob/master/src/utils.ts和https://github.com/mobxjs/mobx-react-lite/blob/master/src/useObserver.ts