无法阅读财产' map'未定义的反应

时间:2017-03-09 11:28:35

标签: reactjs npm

我正在使用fabric-react commandBar组件,其代码与此处给出的相同: fabric-ui-commandbar

但我在运行时遇到以下错误。

Uncaught TypeError: Cannot read property 'map' of undefined 

我的代码如下:

import * as React from 'react';
import { assign } from 'office-ui-fabric-react/lib/Utilities';
import { CommandBar } from 'office-ui-fabric-react/lib/CommandBar';
import { Toggle } from 'office-ui-fabric-react/lib/Toggle';

export class MyPage extends React.Component<any, any> {

  constructor(props: any) {
    super(props);
    this.state = {
      isSearchBoxVisible: true,
      areNamesVisible: true,
      areIconsVisible: true
    };
  }

  public render() {
    let { items, farItems } = this.props;
    let { isSearchBoxVisible: searchBoxVisible, areIconsVisible: iconsVisible, areNamesVisible: namesVisible } = this.state;

    let filteredItems = items.map(item => assign({}, item, {
      name: namesVisible ? item.name : '',
      icon: iconsVisible ? item.icon : ''
    }));

    let filteredFarItems = farItems.map(item => assign({}, item, {
      name: namesVisible ? item.name : '',
      icon: iconsVisible ? item.icon : ''
    }));

    return (
      <div>
        <Toggle
          label='Show search box'
          checked={ searchBoxVisible }
          onChanged={ isSearchBoxVisible => this.setState({ isSearchBoxVisible }) }
          onText='Visible'
          offText='Hidden'
        />
        <Toggle
          label='Show names'
          checked={ namesVisible }
          onChanged={ areNamesVisible => this.setState({ areNamesVisible }) }
          onText='Visible'
          offText='Hidden' />
        <Toggle
          label='Show icons'
          checked={ iconsVisible }
          onChanged={ areIconsVisible => this.setState({ areIconsVisible }) }
          onText='Visible'
          offText='Hidden' />
        <CommandBar
          isSearchBoxVisible={ searchBoxVisible }
          searchPlaceholderText='Search...'
          elipisisAriaLabel='More options'
          items={ filteredItems }
          farItems={ filteredFarItems }
        />
      </div>
    );
  }
}

请帮我解决这个问题? 我已经安装了 Fabric React NPM软件包

1 个答案:

答案 0 :(得分:1)

我认为问题在于您的道具itemsfarItems不是数组。这可能是因为它们确实不是数组,或者当组件首次加载时尚未加载数据,因此道具未定义。

对未加载数据的简单修复是为这些道具提供默认值。在渲染方法中尝试let { items = [], farItems = [] } = this.props;之类的内容。