简体   繁体   English

React String 过滤器方法返回带有 .includes() 条件的空数组

[英]React String filter method returning Empty Array with .includes() conditional

When I test example code like this in a sandbox, it works.当我在沙箱中测试这样的示例代码时,它可以工作。 But when using in my functional component.但是在我的功能组件中使用时。 It does not work.这没用。

I am only showing the code necessary to see the example.我只展示了查看示例所需的代码。 queryValue state is set when a user types in a search bar and have console.log(typeof queryValue) returns a string and console.log(queryValue) to get what is in a field.当用户在搜索栏中键入并让console.log(typeof queryValue)返回字符串和 console.log(queryValue) 以获取字段中的内容时,会设置queryValue状态。

data is an array of objects I am getting from an API. data是我从 API 获取的对象数组。 If queryValue === "" , then data shows up ok.如果queryValue === "" ,则数据显示正常。

else condition when there is something typed in the field, I filter over the data (array of objects) and set the productData to the result of the filter() method. else条件,当在字段中输入某些内容时,我过滤data (对象数组)并将productData设置为filter()方法的结果。 It should only return an array of objects where the title key (which is also a string) includes(queryValue)它应该只返回一个对象数组,其中标题键(也是一个字符串) includes(queryValue)

I have also console.log(product.title.includes(queryValue));我也有console.log(product.title.includes(queryValue)); This returns true At the end console.log(productData);这将返回true最后console.log(productData); and I get an empty array if someone types something...but the condition is true .如果有人输入某些内容,我会得到一个空数组...但条件为true

I read that filter() returns and empty Array if nothing matches the condition.我读到filter()返回,如果没有任何匹配条件,则返回空数组。 But clearly mine does.但显然我的。

product in filter() is confirmed to be an object filter() product被确认为对象

const ExampleComponent = () => {
  const [queryValue, setQueryValue] = useState(null);

  let productData = [];

  if (queryValue === "") {
    productData = data;
  } else {
    productData = data.filter((product) => {
      product.title.includes(queryValue);
    });
  }

  console.log(productData);

  return (
   <h1>Hi</h1>
  )
};

export default ExampleComponent;

Change:改变:

product.title.includes(queryValue);

To return true or false:返回真或假:

return product.title.includes(queryValue);

Or with an implicit return:或者使用隐式返回:

productData = data.filter((product) => product.title.includes(queryValue));

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

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