【问题标题】:Autocomplete with react native使用本机反应自动完成
【发布时间】:2020-04-08 14:21:29
【问题描述】:

谁能帮我调试这段代码,我想使用“react-native-autocomplete-input”库来自动完成搜索文本输入,基本上 api 请求返回股票代码和公司名称的列表,我'正在考虑将此文件存储在本地以使其更快,因为现在我只想使用 fetch 使其工作。自动完成必须在responseJson.symbol中搜索

这是我到目前为止所做的:

import Autocomplete from 'react-native-autocomplete-input';
import React, { Component } from 'react';
import { StyleSheet, Text, TouchableOpacity, Platform,
        ScrollView, View, ActivityIndicator,
        } from 'react-native';

class AutocompleteExample extends Component {
constructor(props) {
    super(props);
    this.state = {
      symbols: [],
      query: '',
    };
  }

searchSymbol(query) {
  if (query === '') {
      return [];
    }

const { symbols } = this.state;
const url = `https://api.iextrading.com/1.0/ref-data/symbols`;

fetch(url)
.then((response) => response.json())
  .then((responseJson) => {
    this.setState({
      symbols:responseJson.symbol,
    });
  })
  .catch((error) => {
    console.error(error);
  });
return symbols;
}

render() {
  if (this.state.isLoading) {
    return (
      <View style={{flex: 1, paddingTop: 20}}>
        <ActivityIndicator />
      </View>
    );
  }
    const { query } = this.state;
    const symbols = this.searchSymbol(query);

    return (

      <ScrollView>
        <View style={styles.MainContainer}>
        <Text style={{fontSize: 12,marginBottom:10}}> Type your favorite stock</Text>
        <Autocomplete
          autoCapitalize={true}
          containerStyle={styles.autocompleteContainer}
          data={symbols}
          defaultValue={query}
          onChangeText={text => this.setState({ query: text })}
          placeholder="Enter symbol"
          renderItem={({ symbol }) => (
            <TouchableOpacity onPress={() => this.setState({ query: symbol })}>
              <Text style={styles.itemText}>
                {symbol}
              </Text>
            </TouchableOpacity>
          )}
        />


      </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({

MainContainer :{
  justifyContent: 'center',
  flex:1,
  paddingTop: (Platform.OS === 'ios') ? 20 : 20,
  padding: 5,
},
autocompleteContainer: {
  borderWidth: 1,
  zIndex:999,
  borderColor: '#87ceeb',
},
itemText: {
  fontSize: 17,
  color:'#000000',
}
});

module.exports = AutocompleteExample

我在控制台上看不到任何错误,并且 api 请求正常工作,我只是无法访问 symbols const 我是否必须渲染类似 cloneWithRows(responseJson.symbols) 的内容?谢谢

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    首先,searchSymbol 方法应该是组件构造函数中的binded,或者声明为class property。否则,“this”将不会指向组件实例。

    然后,您的状态似乎没有 isLoading 属性,但您在渲染函数中使用了它。

    您可能应该做的是在 componentDidMount 生命周期方法中调用异步 searchSymbol 方法。当 fetch 的 promise 解决时,您应该将结果置于 state 中,并将 isLoading 布尔值设置为 false。然后您的组件将使用现在可用的数据重新渲染。

    【讨论】:

      猜你喜欢
      • 2021-09-06
      • 2016-10-13
      • 1970-01-01
      • 2018-12-14
      • 2017-10-04
      • 2018-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多