Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在道具上使用array.prototype.map的React.js返回空数组_Javascript_Arrays_Reactjs - Fatal编程技术网

Javascript 在道具上使用array.prototype.map的React.js返回空数组

Javascript 在道具上使用array.prototype.map的React.js返回空数组,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,我正在深入React的世界,在尝试使用array.prototype.map()将道具的值转换为JSX元素时遇到了一个问题 下面是一个React组件,用于呈现“我的页面”的导航栏:- class NavBar extends React.Component { buttons = this.props.options.map(option => {return <li id={option['option']}>{option['option']}</li>}

我正在深入React的世界,在尝试使用array.prototype.map()将道具的值转换为JSX元素时遇到了一个问题

下面是一个React组件,用于呈现“我的页面”的导航栏:-

class NavBar extends React.Component
{
   buttons = this.props.options.map(option => {return <li id={option['option']}>{option['option']}</li>});

   render()
   {
      return (
         <nav>
            {this.buttons}
         </nav>
      );
   }
}
问题是,当我在NavBar组件中调用this.buttons时,它返回一个空数组。我进行了一些调试,发现在将以下代码添加到渲染函数时:-

<p>{JSON.stringify(this.props.options)}</p>
{JSON.stringify(this.props.options)}

然后,p标记中输出的值将按预期顺利通过,这意味着this.props将正确通过。我还发现,当设置为功能组件时(即,没有类并且在每次出现“props”之前删除“this.”),它可以正常工作

以前有人见过这个错误吗?如果有,你知道是什么导致的吗

谢谢,
Ben

正如@GuyIncognito所解释的,我可以通过将buttons变量移动到render()方法中来解决这个问题


谢谢

>我没有看到代码>构造函数(道具){超级(道具)} /<代码>,为什么你不使用功能组件?你需要把.map放在渲染方法里面。这里需要一个类组件。@GuyIncognito我刚刚尝试了一下,它解决了这个问题,谢谢!
this.state = { 
   options: [
             {'option': 'Button One', 'active': false},
             {'option': 'Button Two', 'active': true},
             {'option': 'Button Three', 'active': false}
            ]
}
<p>{JSON.stringify(this.props.options)}</p>