是否可以在React Native中创建可重用的获取函数?

时间:2018-07-02 09:57:33

标签: node.js react-native

我是React native的新手。

我需要创建一个可重用的提取函数。

所以我将解释我的需求:

  1. 我需要先获取令牌

  2. 获取令牌后,我将请求其他API

  3. 活动编号1将在我每次执行API时执行。

这是我的代码:

fetch('https://myapi.myurl.com/getToken')
  .then((response) => response.json())
  .then((responseJson) => {
   //First API -- Always need to request it to get Token
   fetch('https://myapi.myurl.com/doCheck')
    .then((response) => response.json())
    .then((responseJson) => {

        //My Second API - this API can be change according to case

     });


    });
  

是否可以创建无需更改第二个API的函数   重新编码第一个API调用?如何实现?

谢谢。

3 个答案:

答案 0 :(得分:0)

做这样的事情。

  constructor(props) {
    super(props);

    this.state = {
      data: '',
      token: '',
      flag: 1
    };

    this.fetchData('https://jsonplaceholder.typicode.com/users/1');
    this.fetchData('https://jsonplaceholder.typicode.com/users/2');
  }

  async fetchData(url) {
    await fetch(url)
      .then(response => response.json())
      .then(responseJson => {
        if (this.state.flag) {
          this.setState({ token: responseJson, flag: 0 });
        } else {
          this.setState({ data: responseJson });
        }
      });
  }

  render() {
    const lol = JSON.stringify(data);
    return (
      <View style={styles.container}>
        <Text>API test</Text>
        <Text>{this.state.token.name}</Text>
        <Text>{this.state.data.name}</Text>
      </View>
    );
  }

现在您有了DRY代码。

检查实时python-gitlab

答案 1 :(得分:0)

我的意思是没有违法行为,但是Naaj的代码不起作用,因为获取是一个承诺。

听起来您需要创建一个简单的函数。

您正在处理promise,因此我将进行重写以获得更好的promise-flow,并希望更易于理解;

我会做这样的事情;

   library(dplyr)

# Put the data in a data frame
df <- data.frame(Latitude = c(44.388401,44.388571), Longitude = c(8.433392,8.434575), Altitude =  c(471.000000, 463.000000))

# Extract the two required columns 
start_point <-  df %>% select(Longitude,  Latitude) %>% filter(row_number() == 1)
lat_long <- select(df,  Longitude, Latitude)

# Calculate distance 
df %>% mutate(Distance = distm(lat_long, start_point )) 

然后,您将使用这种方法:

override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap
    // Do other setup activities here too, as described elsewhere in this tutorial.

    // Turn on the My Location layer and the related control on the map.
    updateLocationUI()

    // Get the current location of the device and set the position of the map.
    getDeviceLocation()







                //PRESSING WILL ADD MARKER
                mMap.setOnMapClickListener(GoogleMap.OnMapClickListener { point ->
                    val builder: AlertDialog.Builder
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        builder = AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert)
                    } else {
                        builder = AlertDialog.Builder(this)
                    }
                    val marker = MarkerOptions().position(point)


                    builder.setTitle("Are you sure you want to add a map location here?")


                                . setPositiveButton (android.R.string.yes, DialogInterface.OnClickListener { dialog, which ->
                            mMap.addMarker(marker)
                                    //CUSTOM MARKER
                                    .setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.pinetree_foreground))


                        })

                        .setNegativeButton(android.R.string.no, DialogInterface.OnClickListener { dialog, which ->
                            // do nothing
                        })
                                .show()

                        true


                    }

您可能实际上需要重新编写一点,以将所需的数据注入到需要的位置。就像第一个// You might need a parameter here, but I don't know the details of your API. function doCheckSomething(myParameter) { return fetch('https://myapi.myurl.com/getToken') .then(response => response.json()) .then((responseJson) => { // Return the other promise here, so it will actually resolve on the entire method return fetch('https://myapi.myurl.com/doCheck') }) .then((response) => response.json()) // Moved down for de-nesting. Because we have promises all the way, we can do this. } 进入第二个api检查一样。

答案 2 :(得分:0)

您可以创建一个自定义函数,以使用getToken包装请求:

function myCustomFetch(url, params) {
  return fetch('https://myapi.myurl.com/getToken')
    .then(response => response.json())
    .then((responseToken) => {
      // First API -- Always need to request it to get Token
      return fetch(url, {
        ...params,
        headers: { Authorization: responseToken.token },
      }).then(response => response.json());
    });
}

(请注意,我正在使用对象解构/扩展以便传递headers参数)

然后像这样使用它(例如发出发布请求):

myCustomFetch('https://myapi.myurl.com/doCheck', {
  method: 'POST',
  body: myBodyPayload,
}).then((response) => {
  // do something with response
});