处理HOC来处理子组件API失败

问题描述 投票:0回答:1

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

SO,有没有一种方法可以构建一个高阶组件,该组件可以侦听子组件发出的API请求,或者只是监视DOM的更改以查看长时间未呈现任何内容?

示例-

export default MyComponent extends Component{
    render(){
        <AnalyticsComponent accesstoken={this.props.token} />
    }
}
reactjs google-analytics-api react-hoc
1个回答
0
投票

您可以具有withFetch HOC来注入修改后的访存功能或简单的自定义挂钩。

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
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.