javascript - 在 React 中映射数组时出错

标签 javascript reactjs

我在 React 中映射数组时遇到问题,问题如下: 这是我的父元素的状态:

this.state = {
  grouping: 3,
  bars: [{
    snare: Array(16).fill('0'),
    hihat: Array(16).fill('0'),
    kick: Array(16).fill('0'),
  }]
}

我想将条形传递给子元素,与此相同:

<Bar bar={this.state.bars}>

在“Bar”类中我编写以下代码:

class Bar extends Component {
    render(){
        const Bars = this.props.bars.map((bar)=>{
            return('something')
        }
        return({Bars})
    }
}

在这段代码之后,我出现了这个错误:

对象作为 React 子对象无效(发现:带有键 {Bars} 的对象)。如果您打算渲染子集合,请使用数组。

请帮帮我

最佳答案

您的问题是 React 组件应该只返回 null 或 JSX。

您应该能够通过执行以下操作来获得您想要的内容:

class Bar extends Component {
    render(){
        return(
            {
                this.props.bars.map((bar)=>{
                    return <div>{bar}<div/>
                })
            }
        )
    }
}

关于javascript - 在 React 中映射数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50670925/

相关文章:

javascript - 在 ReactJS 中传递 props 并且它们不会加载,同时收到目标容器错误?

c# - TextBox 值未分配给 asp.net 中的变量

javascript - Webpack & React getComponent() 不加载组件(异步)

javascript - 类属性参数的自动类型推断

javascript - 在 CoffeeScript 对象中添加对象数组

javascript - 无法呈现两个相同的 React 组件,特别是 react-google-chart

javascript - 如果empty = true,则从双层嵌套数组中删除第一个和最后一个项目

JavaScript : How to select elements within one instance of a react class?

html - 在屏幕中心对齐时滚动无法正常工作(使用转换)

testing - React Native 应用程序可以在浏览器中测试吗?