【问题标题】:Async/Await for a search function that calls the api within a react-native-component异步/等待在 react-native-component 中调用 api 的搜索函数
【发布时间】:2020-07-31 14:18:42
【问题描述】:

我是 React Native 新手,需要您的帮助。

我的搜索功能有一个 api 调用,它根据用户输入调用不同的食谱。我在不同的文件中创建了 async/await api 调用。我控制台记录它,一切正常。它在控制台中吐出 json。但是我想在我的 SearchScreen 中实现这个调用,这是下面附加的文件。

在handleSearch 函数中,我调用了getRecipesFromApiByRecipeName(text); 方法的api。 text 是用户输入。

我知道我需要以某种方式创建一个异步函数,以便我可以接收我的 api 调用而不接收

Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}

整个时间。但是如何...

我听说可以在 ComponentDidMount() 函数中进行 api 调用,因为这可以异步进行,但是只有在用户输入查询后才会调用 Api,而不是在安装组件后调用.

我也尝试过使用 .then 函数,它应该以某种方式“取消承诺”Json,但没有运气。

所以我想发生的是,一旦用户给出了输入,就会调用 api,并且可以将 json 添加到屏幕中。如果你能建议我应该做什么,甚至给我看一些代码 sn-ps。也许我攻击这个东西的整个方式是错误的,我想要的只是在设备上显示食谱..所以即使你对如何实现 api 调用有一个全新的想法,让我知道,我真的很感激它。

如果我还需要在此屏幕上修复任何其他问题,请告诉我。

我也很难理解整个“状态”是如何工作的,所以如果这也能解释清楚,将不胜感激。

提前致谢。

import React from 'react';
import {
  FlatList,
  Text,
  View,
  Image,
  TouchableHighlight
} from 'react-native';
import styles from './styles';
import { ListItem, SearchBar } from 'react-native-elements';
import MenuImage from '../../components/MenuImage/MenuImage';
import { getRecipesFromApiByRecipeName } from '../../data/Data';

export default class SearchScreen extends React.Component {
  static navigationOptions = ({ navigation }) => {
    const { params = {} } = navigation.state;
    return {
      headerRight: () =>
        <MenuImage
          onPress={() => {
            navigation.openDrawer();
          }}
        />
      ,
      headerTitle: () =>
        <SearchBar
          containerStyle={{
            backgroundColor: 'transparent',
            borderBottomColor: 'transparent',
            borderTopColor: 'transparent',
            width: 300

          }}
          inputContainerStyle={{
            backgroundColor: '#EDEDED',
            borderRadius: 25
          }}
          inputStyle={{
            backgroundColor: '#EDEDED',
            borderRadius: 5,
            color: 'black'
          }}
          searchIcon
          clearIcon
          onChangeText={text => params.handleSearch(text)}
          placeholder="Search"
          value={params.data}
        />
    };
  };

  constructor(props) {
    super(props);
    this.state = {
      value: '',
      data: []
    };
  }

    componentDidMount() {
    const { navigation } = this.props;
    navigation.setParams({
      handleSearch: this.handleSearch,
      data: this.getValue
    });
  }

  handleSearch = text => {
    const recipes = getRecipesFromApiByRecipeName(text); //need to get this to be able to call await.
      if (text == '') {
        this.setState({
          value: text,
          data: []
        });
      } else {
        this.setState({
          value: text,
          data: recipes
        });
      }
  };

  getValue = () => {
    return this.state.value;
  };

  onPressRecipe = item => {
    this.props.navigation.navigate('Recipe', { item });
  };

  renderRecipes = ({ item }) => (
    <TouchableHighlight underlayColor='rgba(73,182,77,0.9)' onPress={() => this.onPressRecipe(item)}>
      <View style={styles.container}>
        <Image style={styles.photo} source={{ uri: item.recipe.image }} />
        <Text style={styles.title}>{item.recipe.label}</Text>
      </View>
    </TouchableHighlight>
  );

  render() {
    return (
      <View>
        <FlatList
          vertical
          showsVerticalScrollIndicator={false}
          numColumns={2}
          data={this.state.data}
          renderItem={this.renderRecipes}
          keyExtractor={item => `${item.recipeId}`} //How does this work?
        />
      </View>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs react-native async-await


    【解决方案1】:

    根据 JavaScript 的语法规则,关键字 await 只能在 async 函数中执行它需要执行的操作。

    function a() {
      // await is not a keyword in a regular function
      var await = 5;
      console.log(await);
    }
    
    a()
    
    async function b() {
    //^^^
      // but it is a special keyword in an async function
      // by using await, we pause the code execution
      // until the promise we're awaiting one is fulfilled
      const x = await Promise.resolve(10);
      console.log(x);
    }
    
    b();

    这条规则也代表箭头函数:

    const a = () => {
      // await is not a keyword in a regular function
      var await = 5;
      console.log(await);
    }
    
    a()
    
    const b = async () => {
      //      ^^^^^
      // but it is a special keyword in an async function
      // by using await, we pause the code execution
      // until the promise we're awaiting one is fulfilled
      const x = await Promise.resolve(10);
      console.log(x);
    }
    
    b();

    在您的情况下,handleSearch 是常规箭头函数,因此 await 无法在其中工作。您需要将handleSearch 设为async 函数,以在食谱中使用await

    handleSearch = async text => {
    //             ^^^^^
        const recipes = await getRecipesFromApiByRecipeName(text);
    //                  ^^^^^
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 2019-09-29
      • 2021-04-13
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      相关资源
      最近更新 更多