React本机中的通用按钮组件,带有axios api调用的问题

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

我制作了一个常用的按钮组件,正在两个不同的页面中使用。单击按钮后,它将根据道具调用不同的API。

有时,按钮没有调用应该调用的API。它调用了从另一个页面调用的先前的API。

我检查了一下,得出了需要取消订阅异步axios请求的解决方案,但是我不确定在哪里取消订阅API调用以及如何取消订阅。

我正在使用redux saga进行Api呼叫。

下面是我的代码:

import React from 'react';
import {Button, Image, Icon} from 'react-native-elements';


const Button = props => {
  handlePress = () => {
    props.onPress();
  };

  return (
    <>
        <Button
          title={props.title}
          onPress={() => this.handlePress()}
          icon={
            <Image
              source={require('../assets/images/abc.png')}
              style={{marginLeft: ResponsiveWidth(-41)}}
            />
          }></Button>
    </>
  );
};

export default Button;

在组件(1和2)中,我正在按以下方式使用此按钮

<Button onPress={this.handleSubmit}    //Handle submit dispatches different action from component 1 and component 2
reactjs react-native redux axios redux-saga
1个回答
0
投票

您可以使用取消令牌取消请求。

1)您可以使用CancelToken.source工厂创建一个取消令牌,如下所示:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

source.cancel('Operation canceled by the user.');

2)您还可以通过将执行程序函数传递给CancelToken构造函数来创建取消令牌:

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request

cancel();
© www.soinside.com 2019 - 2024. All rights reserved.