【问题标题】:Getting .startsWith() is not a function in react native获取 .startsWith() 不是本机反应中的功能
【发布时间】:2022-01-04 20:19:10
【问题描述】:

我想通过搜索栏搜索项目。原始项目在 prod 中。但我不断得到 startsWith() 不是函数,有时 .toLowerCase() 不是函数

const [prod, setprod] = React.useState([]);
const [getFiltered, setFiltered] = React.useState([]);
const [getSearch,setSearch]=React.useState("");


const SearchItem=(text)=>{
  if(text!=""){
    const searched=prod.filter((item)=>{
      const datachange=item.toLowerCase();
      const textchange= text.toLowerCase();
      return datachange.startsWith(textchange);
    });
    setFiltered(searched);
    setSearch(text)
  }
  else{
    setFiltered(prod);
    setSearch(text);
  }}

【问题讨论】:

  • 我们需要看看你是如何填写prod的,以及你在哪里打电话给SearchItem

标签: javascript arrays reactjs react-native


【解决方案1】:

我同意@lucasvw 的观点,在这里提供更多信息会有所帮助。

但是,您的条件仅验证 text!="",但如果文本是其他内容,例如数字、函数或(更有可能)undefinednull,则会抛出此错误。

我建议改成这样:

if (typeof text === "string" && text != "") {
# the rest of your code
}

编辑:

抱歉,实际上是item在扔东西。

同样的想法,但试试这个:

    const searched=prod.filter((item)=>{
      if (typeof item !== "string") {
        return false;
      }
      const datachange=item.toLowerCase();
      const textchange= text.toLowerCase();
      return datachange.startsWith(textchange);
    });

【讨论】:

    猜你喜欢
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 2021-08-18
    • 1970-01-01
    • 2020-02-04
    • 2022-01-21
    相关资源
    最近更新 更多