简体   繁体   English

Array.some 在我的 React 组件中不起作用,但 Array.map 是

[英]Array.some is not working inside my React component, but Array.map is

I'm trying to use Array.prototype.some() inside my React component to determine if my array of objects has a certain value, but I'm getting the error data.some(...) is not a function .我试图在我的 React 组件中使用Array.prototype.some()来确定我的对象数组是否具有特定值,但我收到错误data.some(...) is not a function Array.prototype.map() is working fine. Array.prototype.map()工作正常。

My data is an array of objects from MongoDB.我的data是来自 MongoDB 的对象数组。

data = [
 {_id: 'foobar', category: 'sleep'}, {}, ...
]

Here's the component with the props being passed down:这是传递道具的组件:

<Component
  data={data}
  category='sleep'
/>

The component:组件:

import ChildComponent from "../components/ChildComponent";

const Component = ({ data, category }) => {
  return ( 
    <>
      {data && data.some(e => e.category === category) (
        <h3>{category}</h3>
      )}

      {data && data.map(e => {
        return gear.category === category &&
          <ChildComponent 
            key={e._id} 
            e={e}
          />
      })}
    </> 
   );
}
 
export default Component;

Why would .map work but not .some ?为什么.map可以工作,但.some

Array.map(...) returns an array. Array.map(...)返回一个数组。 Array.some(...) returns a boolean. Array.some(...)返回一个 boolean。

Made a mistake with the logic, should be:搞错了逻辑,应该是:

{data && data.some(e => e.category === category) && <h3>{category}</h3>}

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

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