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

时间:2019-11-24 20:19:35

标签: reactjs react-hooks map-function

我有一组对象,它们作为道具传递给子组件。在子组件中,我想映射该数组以显示在列表中。但是我遇到了这个错误

  

试图破坏不可迭代实例的无效尝试

这是我的孩子:

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>
  );
};

这是我的父母

 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不是函数   我认为我的问题是道具变形。但是我不知道该怎么做。   希望我的问题很清楚。

4 个答案:

答案 0 :(得分:1)

@Clarity在评论中指出,我通过更改来解决了问题

const [parentProps] = props;

const parentProps = props;

parentProps.map((content) => (

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

答案 1 :(得分:1)

您应该像这样破坏列表道具,然后映射该变量:

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

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

答案 2 :(得分:0)

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

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

  

试图破坏不可迭代实例的无效尝试

在销毁对象时,应在析构函数中传递要从源对象获取的字段。可以在这里找到更多信息:

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

答案 3 :(得分:-1)

您应该使用

props.parentProps.map(content => {...})
相关问题