【问题标题】:React.js using array.prototype.map on props returns empty arrayReact.js 在 props 上使用 array.prototype.map 返回空数组
【发布时间】:2020-08-31 18:30:59
【问题描述】:

我正在涉足 React 世界,但在尝试使用 array.prototype.map() (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) 将 props 的值转换为 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 options={this.state.options}/>

在哪里:-

this.state = { 
   options: [
             {'option': 'Button One', 'active': false},
             {'option': 'Button Two', 'active': true},
             {'option': 'Button Three', 'active': false}
            ]
}

问题是当我在 NavBar 组件中调用 this.buttons 时,它返回一个空数组。我做了一点调试,发现在渲染函数中添加以下代码时:-

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

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

以前有没有人见过这个错误,如果有,你知道是什么原因造成的吗?

谢谢, 本

【问题讨论】:

  • 我没有看到 constructor(props) { super(props); } 还有你为什么不使用功能组件?
  • 你需要把.map放到render方法里面。
  • @DominikMatis 我确实考虑在这种情况下使用功能组件,但是鉴于 NavBar 组件应该将信息传递回其父组件,因此这里需要一个类组件。
  • @GuyIncognito 我刚刚试了一下,它解决了问题,谢谢!

标签: javascript arrays reactjs


【解决方案1】:

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

谢谢!

【讨论】:

    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 2021-05-13
    • 2022-06-15
    • 1970-01-01
    • 2014-05-03
    • 2021-10-22
    • 2022-07-27
    • 1970-01-01
    相关资源
    最近更新 更多