反应挂钩:无法使用地图功能创建列表

react hooks: Can't create list with map function

我有一个 objects 数组作为道具传递给 child 组件。在 child 组件中,我想映射该数组以显示在列表中。但是我收到了这个错误

Invalid attempt to destructure non-iterable instance

这是我的 child :

const ServiceTabs = (props) => {
  const [parentProps] = props;
  return (
    <ul>
      {
          parentProps.map((content) => (
            <li key={content.id} className="active">
              <BtnButton
                btnStyle={content.btnStyle}
                btnColor={content.btnColor}
                customTitle={content.customTitle}
                IconSRC={content.IconSRC}
              />
            </li>
          ))
}
    </ul>
  );
};

这是我的 parent:

 const ServiceCategory = () => {
      const [serviceState, setserviceState] = useState([
        {
          id: 1,
          customtitle: 'hair', 
          btnStyle: {
            backgroundColor: '#fff',
            width: '100px',
            height: '100px',
            flexDirection: 'column',

          },
        },
        {
          id: 2,
          .
          .
          },        
      ]);
.
.
.
 <ServiceTabs list={serviceState} />

当我将 const [parentProps] = props; 更改为 const parentProps = props; 时,错误会发生变化:

parentProps.map is not a function i think my problem is destructure of props.but i dont know how to do that. hope my question was clear.

你应该使用

props.parentProps.map(content => {...})

正如@Clarity 在评论中指出的那样,我通过更改

解决了问题
const [parentProps] = props;

const parentProps = props;

parentProps.map((content) => (

parentProps.list.map((content) => (

const [parentProps] = props;更改为const {list: parentProps} = props;

请注意,此上下文中的 [] 用于解构数组,这就是它显示错误的原因:

Invalid attempt to destructure non-iterable instance

当你解构一个对象时,你应该在析构函数中传递你想从源对象中获取的字段。可以在这里找到更多信息:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

你应该像这样解构列表属性然后映射到那个变量:

const { list } = props
list.map(content => {...})

这是一个有效的 Codesandbox 示例(大部分)使用您的代码来说明我的意思:https://codesandbox.io/s/distracted-pasteur-k8387?fontsize=14&hidenavigation=1&theme=dark