我有一个函数组件,我想强制它重新渲染。

我该怎么做呢? 因为没有实例this,所以我不能调用this. forceupdate()。


当前回答

官方常见问题现在推荐这种方式,如果你真的需要这样做:

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

  function handleClick() {
    forceUpdate();
  }

其他回答

最佳方法-没有多余的变量重新创建在每次渲染:

const forceUpdateReducer = (i) => i + 1

export const useForceUpdate = () => {
  const [, forceUpdate] = useReducer(forceUpdateReducer, 0)
  return forceUpdate
}

用法:

const forceUpdate = useForceUpdate()

forceUpdate()

这可以在不显式使用钩子的情况下完成,只要你给你的组件添加一个道具,给无状态组件的父组件添加一个状态:

const ParentComponent = props => {
  const [updateNow, setUpdateNow] = useState(true)

  const updateFunc = () => {
    setUpdateNow(!updateNow)
  }

  const MyComponent = props => {
    return (<div> .... </div>)
  }

  const MyButtonComponent = props => {
    return (<div> <input type="button" onClick={props.updateFunc} />.... </div>)
  }

  return (
    <div> 
      <MyComponent updateMe={updateNow} />
      <MyButtonComponent updateFunc={updateFunc}/>
    </div>
  )
}

官方常见问题现在推荐这种方式,如果你真的需要这样做:

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

  function handleClick() {
    forceUpdate();
  }

公认的答案是好的。 只是为了更容易理解。

示例组件:

export default function MyComponent(props) {

    const [updateView, setUpdateView] = useState(0);

    return (
        <>
            <span style={{ display: "none" }}>{updateView}</span>
        </>
    );
}

强制重新渲染调用下面的代码:

setUpdateView((updateView) => ++updateView);

如果你已经在函数组件中有一个状态,而你不想改变它并需要重新呈现,你可以伪造一个状态更新,这将反过来重新呈现组件

const [items,setItems] = useState({
   name:'Your Name',
   status: 'Idle'
})
const reRender = () =>{
setItems((state) => [...state])
}

这将保持状态不变,并将做出反应,认为状态已更新