gpt4 book ai didi

javascript - 如何强制渲染功能性 React 组件?

转载 作者:行者123 更新时间:2023-12-03 12:54:50 59 4
gpt4 key购买 nike

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

我该怎么做?
由于没有实例 this,我无法调用 this.forceUpdate()

最佳答案

🎉 现在可以使用 React hooks

使用 React hooks,您现在可以在函数组件中调用 useState()

useState() 将返回包含 2 个内容的数组:

  1. 一个值,代表当前状态。
  2. 它的设置者。用它来更新值。

通过 setter 更新值将强制您的函数组件重新渲染
就像 forceUpdate 所做的那样:

import React, { useState } from 'react';

//create your forceUpdate hook
function useForceUpdate(){
const [value, setValue] = useState(0); // integer state
return () => setValue(value => value + 1); // update state to force render
// A function that increment 👆🏻 the previous state like here
// is better than directly setting `setValue(value + 1)`
}

function MyComponent() {
// call your hook here
const forceUpdate = useForceUpdate();

return (
<div>
{/*Clicking on the button will force to re-render like force update does */}
<button onClick={forceUpdate}>
Click to re-render
</button>
</div>
);
}

You can find a demo here .

上面的组件使用自定义钩子(Hook)函数(useForceUpdate),该函数使用 react 状态钩子(Hook)useState。它增加组件的状态值,从而告诉 React 重新渲染组件。

编辑

在此答案的旧版本中,代码片段使用了 bool 值,并在 forceUpdate() 中切换它。现在我已经编辑了答案,该代码片段使用数字而不是 bool 值。

为什么?(你会问我)

因为有一次我碰巧我的 forceUpdate() 随后从两个不同的事件调用了两次,因此它将 bool 值重置为其原始状态,并且组件从未呈现。

这是因为在 useState 的 setter 中(这里是 setValue),React 会将之前的状态与新的状态进行比较,并且仅在状态不同时才渲染。

关于javascript - 如何强制渲染功能性 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46240647/

59 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com