繁体   English   中英

从 componentDidUpdate 生命周期方法重写 useEffect 钩子

[英]Rewrite useEffect hook from componentDidUpdate lifecycle method

假设我们有一个买家 ID 的输入,并且我们希望在每次买家 ID 更改时获取买家详细信息。 class 组件的以下代码如下所示

componentDidUpdate(prevProps,prevState) {
  if (this.state.buyerId !== prevState.buyerId) {
    this.props.fetchBuyerData(this.state.buyerId); // some random API to search for details of buyer
  }
}

但是如果我们想在功能组件中使用 useEffect 钩子,我们将如何控制它。 我们如何将以前的道具与新道具进行比较。

如果我按照我的理解来写它会有点像这样。

useEffect(() => {
    props.fetchBuyerData(state.buyerId); 
}, [state.buyerId]);

但是随后 react 的 hooks linter 建议我也需要将 props 包含到依赖数组中,如果我在依赖数组中包含 props,一旦 props 发生更改,根据要求不正确,就会立即调用 useEffect。 如果唯一目的是进行 API 调用,有人可以帮助我理解为什么依赖数组中需要道具。 还有什么方法可以控制以前的 state 或道具进行深度比较,或者只是控制 function 在 useEffect 中的执行。

在 function 声明中或组件内部解构道具。 当在fetchBuyerData钩子中使用useEffect时,只需将其列为依赖项而不是所有props

// deconstruct in declaration
function MyComponent({ fetchBuyerData }) {
  useEffect(() => {
    // caveat: something is wrong with the use of `this.state` here
    fetchBuyerData(this.state.buyerId); 
  }, [fetchBuyerData, state.buyerId]);
}

// deconstruct inside component
function MyComponent(props) {
  const { fetchBuyerData } = props;
  useEffect(() => {
    // caveat: something is wrong with the use of `this.state` here
    fetchBuyerData(this.state.buyerId); 
  }, [fetchBuyerData, state.buyerId]);
}

我假设您正在重写您的 class 组件信息功能之一。 那么你最好在你设置新的state.bayerId的地方包含你的fetch请求(我认为它不是外部道具)。 就像是:

const [buyerId, setBuyerId] = React.useState('')

const handleOnChange = (ev) => {
  const { value } = ev.target

  if (value !== buyerId) {
    props.fetchBuyerData(value)
    setBuyerId(value)
  }
...

  return (
    <input onChange={handleOnChange} value={buyerId} />
...

代码片段有些欠佳。 对于生产,我假设将更改处理程序包装到useCallback中,以便不会在每次渲染时重新创建它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM