【问题标题】:React HOC to handel child component API failureReact HOC 处理子组件 API 失败
【发布时间】:2020-02-21 13:09:54
【问题描述】:

我正在使用库中的一个组件,该组件接受 accessToken 作为道具。喜欢 <AnalyticsChart accesstoken={this.state.token} /> 并根据令牌进行 API 调用并根据结果呈现 UI。现在,如果 accesstoken 已过期,它没有回调 props 来通知父组件(我可以完全控制它)。

那么,有没有办法构建一个高阶组件,它可以监听子组件发出的 API 请求,或者只是观察 DOM 更改以查看是否长时间没有渲染?

例子-

export default MyComponent extends Component{
    render(){
        <AnalyticsComponent accesstoken={this.props.token} />
    }
}

【问题讨论】:

  • 在你的MyComponent中使用componentDidUpdate怎么样

标签: reactjs google-analytics-api react-hoc


【解决方案1】:

您可以使用withFetch HOC 来注入您修改后的 fetch 函数或简单的自定义挂钩。

1. HOC 实现

// UNTESTED
function withFetch(Component) {
  return function(props) {
    const [error, setError] = React.useState(false);

    // modified fetch
    const doFetch = React.useCallback((url, options) => {
      try {
        fetch(url, options)
        // proceed if successful
      } catch(error) {
        setError(true);
        // TODO: add other states to store error message
      }
    }, [params])

    // run effect every time there's fetch error
    React.useEffect(() => {
      if (error) {
        // TODO: do something
      }
    }, [error]);

    return <Component fetch={doFetch} {...props} />
  }
}

const EnhancedComponent = withFetch(MyComponent)
return <EnhancedComponent accessToken="some token" />

2。自定义挂钩

function hasFetchError(url, options) {
  const [error, setError] = React.useState(false);

  React.useEffect(() => {
    async function doFetch() {
      try {
        await fetch(url, options)
        // do something with response
      } catch(error) {
        setError(true);
      }
    }
    doFetch();
  }, [url, options])

  return error;
}

// Usage:
function MyComponent(props) {
  const error = hasFetchError(props.url, props.options);
  if (error) {
    // do something
  }
}

【讨论】:

  • 如果你使用钩子,为什么不做一个自定义钩子而不是使用钩子的HOC
  • @ShubhamKhatri 是的。只是与OP要求HOC有关。为了简洁起见,我添加了一个简单的自定义钩子。
  • 你能像这样在 useEffect 中进行回调吗?另外,我认为第一个不会起作用,因为您在回调中使用了钩子。我现在正在与之抗争
猜你喜欢
  • 1970-01-01
  • 2012-05-10
  • 2020-06-10
  • 1970-01-01
  • 1970-01-01
  • 2019-10-18
  • 2016-10-20
  • 1970-01-01
  • 2017-04-03
相关资源
最近更新 更多