Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

reactjs - React, can you make an array of elements with Array(n).fill(0).map?

It seems you can not, but I can not nail down why.

Here is my code that is causing the problem :

class App extends React.Component {

  render() {

    var elems = Array(~~(this.props.number)).fill(0).map( ()=> <div>test</div>);

    console.log(elems); //(5) [Object,Object,Object,Object,Object]

    return (
      {elems}
    )
  }
}

ReactDOM.render(<App number='5' />, document.querySelector('#app'))

The error points me to a page in the docs that says 'valid React element (or null) must be returned.'

Im following the example here

https://facebook.github.io/react/docs/lists-and-keys.html (Basic List Component)

thats using an array, so its possible, but somehow mines different.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As @Andrew Li pointed out, the original code is returning an non-React Element object which is the source of the error. React expects an object to be returned but the type, {elems: elems}, is invalid.

A React component may only (currently) return a single Element (see the caveat in the React Component docs) and not an array. Wrapping your array with a parent should do the trick.

class App extends React.Component {

  render() {

    var arr = Array(~~(this.props.number)).fill(0).map( ()=> <div>test</div>);

    return (
      <div>
        {elems}
      </div>
    )
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...