【问题标题】:Rewrite useEffect hook from componentDidUpdate lifecycle method从 componentDidUpdate 生命周期方法重写 useEffect 钩子
【发布时间】:2021-08-21 19:35:34
【问题描述】:

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

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 调用,有人可以帮助我理解为什么依赖数组中需要 props。 还有什么方法可以控制之前的状态或道具进行深度比较,或者只是控制 useEffect 中的函数执行。

【问题讨论】:

  • 您对this关键字的使用不正确。你如何使用useState

标签: javascript reactjs react-hooks


【解决方案1】:

在函数声明或组件内部解构 props。当fetchBuyerDatauseEffect 钩子中使用时,只需将其列为依赖项而不是所有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]);
}

【讨论】:

  • 但是如果 fetchBuyerData(一个描述 API 调用的动作)除了获取买家的数据之外没有其他目的,为什么要把它包含在依赖数组中。我无法消化这个事实。你能帮忙吗?
  • ESLint 无法知道程序执行时引用会保持不变,ESLint 是一个静态分析工具。 知道函数不会改变,但是 ESLint 不可能知道引用在运行时会保持不变,因为 ESLint 不会运行你的代码。
  • ESLint hooks 插件对从useState (github.com/facebook/react/blob/…) 返回的回调有特殊处理 将来可能会注释你知道不会改变的值,但现在它们都应该列在 deps 数组中。
【解决方案2】:

我假设您正在重写您的类组件信息功能之一。那么你最好在你设置新的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} />
...

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

【讨论】:

  • 这更多的是一个示例,但实时适用性使我在某些状态发生更改时在 useEffect 内部进行 api 调用,在这种情况下,为什么需要将 props.fetchBuyerData 包含到依赖数组。这对我来说有点不清楚。
  • 如果buyerIdstate 对象内部的一个外部属性,那么就按原样使用它。只需更正您的代码。 useEffect 箭头函数内部没有this。在fetchBuyerData 调用中使用state.buyerId
猜你喜欢
  • 2019-12-12
  • 1970-01-01
  • 2021-03-27
  • 2020-01-15
  • 2017-11-22
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
相关资源
最近更新 更多