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

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


当前回答

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

const forceUpdateReducer = (i) => i + 1

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

用法:

const forceUpdate = useForceUpdate()

forceUpdate()

其他回答

对我来说,仅仅更新状态是行不通的。我正在使用带有组件的库,看起来我不能强制组件更新。

我的方法是用条件渲染扩展上面的方法。在我的例子中,我想在值改变时调整组件的大小。

//hook to force updating the component on specific change
const useUpdateOnChange = (change: unknown): boolean => {
  const [update, setUpdate] = useState(false);

  useEffect(() => {
    setUpdate(!update);
  }, [change]);

  useEffect(() => {
    if (!update) setUpdate(true);
  }, [update]);

  return update;
};

const MyComponent = () => {
  const [myState, setMyState] = useState();
  const update = useUpdateOnChange(myState);

  ...

  return (
    <div>
      ... ...
      {update && <LibraryComponent />}
    </div>
  );
};

您需要传递想要跟踪更改的值。钩子返回用于条件呈现的布尔值。

当更改值触发时,useEffect更新将变为false,从而隐藏组件。在此之后,第二个useEffect被触发,update变为true,这使得组件再次可见,并导致更新(在我的例子中是调整大小)。

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

示例组件:

export default function MyComponent(props) {

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

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

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

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

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

const forceUpdateReducer = (i) => i + 1

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

用法:

const forceUpdate = useForceUpdate()

forceUpdate()

我使用了一个第三方库 use-force-update 强制渲染我的react功能组件。工作很有魅力。 只需在项目中使用import包并像这样使用。

import useForceUpdate from 'use-force-update';

const MyButton = () => {

  const forceUpdate = useForceUpdate();

  const handleClick = () => {
    alert('I will re-render now.');
    forceUpdate();
  };

  return <button onClick={handleClick} />;
};

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

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

  function handleClick() {
    forceUpdate();
  }