0

这是我的代码

SearchFilterFunction(text) {
callApi = async () => {
  try {
    const response = await 
fetch('http://192.168.100.229:9085/api/V1AndroidUnAuthorizedFastSearch? 
title=${text}');
    const responseJson = await response.json();
    this.setState({
      isLoading: false,
      dataSource: responseJson.data,
    }, function () {
    });
  }
  catch (error) {
    console.error(error);
  }
 }
}


render() {

return (

  <View style={{ flexDirection: 'column' }}>

    <View style={{
      flexDirection: 'column',
      alignItems: 'stretch',
    }}>
      <View style={{
        height: 50,
        backgroundColor: '#008cff',
        flexDirection: 'row',
        justifyContent: 'space-between'

      }} >
        <Image source={require('./asset/ic_buy_package.png')}
          style={{ width: 30, height: 30, marginTop: 10, marginLeft: 10 }} 
  />

        <Image source={require('./asset/img_logo.png')}
          style={{ width: 30, height: 30, marginTop: 10 }} />

        <TouchableHighlight onPress={this.callApi}>
          <Image source={require('./asset/ic_menu.png') }
            style={{ width: 30, height: 30, marginTop: 10, marginRight: 
  10, }}
          />
        </TouchableHighlight>
      </View>
    </View>

    <View style={{
      height: 50,
      backgroundColor: "#008cff"
    }}>
      <TextInput
        style={{ height: 40, backgroundColor: '#ffffff', marginRight: 10, 
   marginLeft: 10, marginTop: 5, textAlign: 'right', paddingRight: 10 }}
        placeholder='جستجو...'

      onChangeText={text => this.SearchFilterFunction(text).callApi}
      onClear={text => this.SearchFilterFunction().callApi}
      />

    </View>

    <Text>{this.state.input}</Text>

    <FlatList
      data={this.state.dataSource}
      renderItem={({item}) => <Text style={{fontSize:15,margin:10}}> 
    {item.title}</Text>}
      keyExtractor={({id}, index) => id}
    />
  </View>


   );
  }
 };

但是当输入 TextInput 我得到这个错误

undefined 不是对象(评估'_this3.searchfilterfunction(text).callApi'

我想从 TextInput 获取文本并使用输入的文本获取我的 API。

4

1 回答 1

1

这里有几个问题:

1)您在函数内部定义一个函数

SearchFilterFunction(text) {
callApi = async () => {

2) 如果要在字符串中插入变量值,请使用 ` 而不是 '。

3)这个函数调用不起作用this.SearchFilterFunction(text).callApi

修改:

将您的功能更改为 SearchFilterFunction 以:

async SearchFilterFunction(text) {
try {
  const response = await 
  fetch(`http://192.168.100.229:9085/api/V1AndroidUnAuthorizedFastSearch? 
   title=${text}`);

  const responseJson = await response.json();
  console.log('response', responseJson); 
  // set your state here 
}
catch (error) {
  console.error(error);
}
}

将您的 TextInput 更改为:

 <TextInput
  style={{ height: 40, backgroundColor: '#ffffff', marginRight: 10, 
  marginLeft: 10, marginTop: 5, textAlign: 'right', paddingRight: 10 }}

  onChangeText={text => this.SearchFilterFunction(text)}
  onClear={text => this.SearchFilterFunction()}
 />

工作示例:

我在这里创建了一个简化的工作示例:

https://snack.expo.io/S1LWHvH2V

于 2019-05-12T09:19:56.887 回答