map function loop when rendering with ReactJS and concat JSX syntax

佐手、 提交于 2019-12-23 03:22:31

问题


very simple question, when I loop through array when rendering react compnent with .map function, say:

render() {
        let board = this.props.board;

        return (
            <div>
                 {
                   board.map((piece,index) => {
                       return (
                           <Piece data={piece}/>
                       );
                   })
                 }
            </div>
        );
    }

I'm trying to add a break line every 5 pieces so (index % 5 == 0) add <br /> before the <Piece />
when I try to concatinate with + or to do something like this:

board.map((piece,index) => {
      return (
                (index % 5 == 0) ? <br /> : ''
                <Piece data={piece}/>
             );
})

I'm getting an output of matrix of [Object object]'s


回答1:


Return an array of [ <br />, <Piece> ] if the condition holds and return just the Piece component otherwise. See the fiddle.

The relevant piece of code is this:

return <div>{items.map(function (i, index) {
    if (index % 5 === 0) {
        return [ <br key={index + "break"} />, <Item key={index} num={i} /> ];
    }

    return <Item key={index} num={i} />;
})}</div>;

Also, put key on the components you return from map or other ways that return array-like instances. This way, React doesn't need to take out all the generated components and replace them on each render, but can just find them under the key and update their attributes. Check out Reconciliation in React docs to learn more.



来源:https://stackoverflow.com/questions/33855585/map-function-loop-when-rendering-with-reactjs-and-concat-jsx-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!