如何修复错误:item[_this.props.text_key].split不是一个函数



我正在为搜索输入中的自动建议设置一个新功能,对于某些单词,它给了我一个错误,上面写着:"item[_this.props.text_key].split 不是一个函数"。

看起来 API 有时会返回一个对象,而不是一个字符串。

这是我为文本输入中的搜索建议制作的新组件。

getSuggestions = async currentSearch => {
    try {
      const response = await Api.serachOutoCompleate(currentSearch)
      let searchAutoComplete = response.suggestions.products.map(product => product.product_title)
      response.suggestions.categories.forEach(categories => searchAutoComplete.push(categories))
      response.suggestions.warehouses.forEach(warehouse => searchAutoComplete.push(warehouse.warehouse_name))
      response.suggestions.upcs.forEach(upcs => searchAutoComplete.push(upcs.product_title))
      response.suggestions.tags.forEach(tags => searchAutoComplete.push(tags.product_title))
      this.storedResults[currentSearch] = response
      if (mounted && currentSearch && searchAutoComplete) this.setState({ currentSearch: currentSearch, searchAutoComplete: searchAutoComplete, response })
      else this.setState({ currentSearch: currentSearch })
    } catch (error) {
      console.log(error)
    }
  }

我希望不会收到错误.

看起来 API 有时会返回一个对象,而不是一个字符串。

所以问题出在 API 上...请更改您的问题并显示 API 代码。

如果您只想避免错误,则可以进行一些检查

const splittedName = typeof item[this.props.text_key] === "string" ? item[this.props.text_key].split(' ') : []

这将停止错误,但是当item[this.props.text_key]是一个对象时,您将获得一个空数组,并且不会显示您想要的内容(因为您没有显示数据(

我要做的是其中之一:

  • 修复 API 以始终获取字符串
  • 做一些调试(你可以做一个console.log(,看看item[this.props.text_key]有什么,然后做一些检查来得到你想要的。

仅凭您提供的信息,这是我能为您提供的最大帮助。

最新更新