首页 > 解决方案 > TypeError: undefined is not an object (evalating '_this.state.data.name.filter') 反应原生

问题描述

react-native的过滤功能中如何使用对象?基本上,我的 react native 应用程序中有一个自动完成功能,所以我使用 react-native-autocomplete-input 包,我从服务器收到的数据是对象,数据就是这样

"student": [
  {
    "id": 1,
    "name": "roger",
    "created_at": "2021-03-04T13:02:11.000000Z",
    "updated_at": "2021-03-04T13:02:11.000000Z"
  },
  {
    "id": 2,
    "name": "federe",
    "created_at": "2021-03-04T13:02:11.000000Z",
    "updated_at": "2021-03-04T13:02:11.000000Z"
  },
...

我的自动完成就是这样

<Autocomplete
  autoCapitalize="none"
  autoCorrect={false}
  data={this.state.student}
  listViewDisplayed="auto"
  // Default value if you want to set something in input
  defaultValue={
    this.state.selectedstudent === '' ?
    '' :
    this.state.selectedstudent.name
  }
  // Onchange of the text changing the state of the query
  // Which will trigger the findstudent method
  // To show the suggestions
  onChangeText={(text) => this.findstudent(text)}
  placeholder="Enter Student Name"
  renderItem={({ item }) => (
    // For the suggestion view
    <TouchableOpacity
      onPress={() => {
        this.setState({ selectedstudent: item });
        this.setState({ filteredstudent: '' });
      }}>
      <Text style={{ color: red }}>
        {item}
      </Text>
    </TouchableOpacity>
  )}
/>

改变时,功能就是这样

findstudent = (query) => {
  // Method called every time when we change the value of the input
  if (query) {
    // Making a case insensitive regular expression
    const regex = new RegExp(`${query.trim()}`, 'i');
    // Setting the filtered student array according the query
   this.setState({ filteredstudent: this.state.student.filter((text) => text.name.search(regex) >= 0) });
    } else {
      // If the query is null then return blank
      this.setState({ filteredstudent: '' });
      console.log(this.state.filteredstudent)
    }
  }

但它给了我那个错误

Error: Objects are not valid as a React child (found: object with keys {id, name, create_at,updated_at}). If you meant to render a collection of children, use an array instead.

所以我只想在自动完成输入中显示学生的姓名,当他选择任何用户时,通过 fetch 方法将他的 id 发送到我的服务器

标签: react-nativeautocomplete

解决方案


推荐阅读