简体   繁体   English

undifined 不是 React Native 中的 object

[英]undifined is not an object in react native

I'm making an autocomplete with react native.我正在使用 React Native 进行自动完成。 I pulled the data from the API我从 API 中提取数据

The following is the API list:以下为API名单:

{
  "status": 200,
  "error": false,
  "kecamatan": [
    {
      "id_kecamatan": "1",
      "kecamatan": "Gambir",
      "kode": "CGK12020",
      "id_kota": "1",
      "kota": "Jakarta Pusat",
      "id_provinsi": "1",
      "provinsi": "DKI Jakarta"
    },
    {
      "id_kecamatan": "2",
      "kecamatan": "Tanah Abang",
      "kode": "CGK12080",
      "id_kota": "1",
      "kota": "Jakarta Pusat",
      "id_provinsi": "1",
      "provinsi": "DKI Jakarta"
    },
]
}

when i get with fetch, i get into trouble ie,当我使用 fetch 时,我遇到了麻烦,即,

undifined is not an object in (evaluating kecamatan.filter) undifined 不是 object(评估 kecamatan.filter)

here is my code这是我的代码

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

  componentDidMount() {
    fetch(`${API}/kecamatan/`)
      .then(res => res.json())
      .then((json) => {
        console.log(json)
        const { results: kecamatan } = json;
        this.setState({ kecamatan });
      });
  }

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

    const { kecamatan } = this.state;
    const regex = new RegExp(`${query.trim()}`, 'i');
    return kecamatan.filter(kecamatan => kecamatan.kecamatan.search(regex) >= 0);
  }

  render() {
    const { query } = this.state;
    const kecamatan = this.find(query);
    const comp = (a, b) => a.toLowerCase().trim() === b.toLowerCase().trim();

    return (
      <View style={styles.container}>
          <Autocomplete
            autoCapitalize="none"
            autoCorrect={false}
            containerStyle={styles.autocompleteContainer}
            data={kecamatan.length === 1 && comp(query, kecamatan[0].kecamatan) ? [] : kecamatan}
            defaultValue={query}
            onChangeText={text => this.setState({ query: text })}
            placeholder="Enter Star Wars film title"
            renderItem={({ item }) => (
              <TouchableOpacity
                onPress={() => this.setState({ query: item.kecamatan })}
              >
                <Text style={styles.itemText}>{item.kecamatan}</Text>
              </TouchableOpacity>
            )}

          />
      </View>
    );
  }

please correct, this condition I want to find the name of the district using autocomplete, where I am wrong请更正,这种情况我想使用自动完成查找地区名称,我错了

componentDidMount() {
fetch(`${API}/kecamatan/`)
  .then(res => res.json())
  .then((json) => {
    console.log(json)
    const { results: kecamatan } = json;
    this.setState({ kecamatan });
  });

} }

Change const { results: kecamatan } to const { kecamatan } and then it will properly assign it to the state.const { results: kecamatan }更改为const { kecamatan }然后它将正确分配给 state。

I see 2 problems in your filter function:我在您的过滤器 function 中看到 2 个问题:

You're extracting kecamatan from state incorrectly, it should be:您错误地从 state 中提取了 kecamatan,它应该是:

const { kecamatan } = this.state;

You're using the same name for the array and the item, you should use a different name inside your filter like this:您为数组和项目使用相同的名称,您应该在过滤器中使用不同的名称,如下所示:

return kecamatan.filter(item => item.kecamatan.search(regex) >= 0);

results is not defined on the API response. results未在 API 响应中定义。

So when you do const { results: kecamatan } = json;所以当你做const { results: kecamatan } = json; , kecamatan is undefined, which you then set to state. So replace this with const { kecamatan } = json; , kecamatan未定义,然后将其设置为 state。因此将其替换为const { kecamatan } = json;

You have kecamatan.kecamatan.search(regex) >= 0)你有kecamatan.kecamatan.search(regex) >= 0)

I do not think you have 2 layers of kecamatan as you already pulled it out of the state above?我不认为你有 2 层kecamatan ,因为你已经把它从上面的 state 中拉出来了?

const { kecamatan } = this.state;

Your kecamatan array is undefined because of the way you have set your fetch results.由于您设置获取结果的方式,您的kecamatan数组undefined result is not a key on the returned JSON, so you are trying to filter on undefined . result不是返回的 JSON 上的键,因此您正在尝试过滤undefined You want const { kecamatan } = json;你想要const { kecamatan } = json;

If your fetch does ever come back as undefined , you can guard your filter operation (ie instead of return kecamatan.filter(result =>... , you could do return (kecamatan || []).filter(result =>... (or in recent Typescript return kecamatan?.filter(result =>... .如果你的 fetch 确实返回为undefined ,你可以保护你的过滤器操作(即不是return kecamatan.filter(result =>... ,你可以return (kecamatan || []).filter(result =>... (或最近 Typescript return kecamatan?.filter(result =>... .

Also, don't name your iterable the same as its member, you may get unexpected effects.另外,不要将您的可迭代对象命名为与其成员相同的名称,您可能会得到意想不到的效果。 This is why I changed kecamatan.filter(kecamatan => to kecamatan.filter(result => .这就是为什么我将kecamatan.filter(kecamatan =>更改为kecamatan.filter(result =>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM