简体   繁体   English

如何在ReactJS中使用地图渲染数组的引导网格

[英]How to render bootstrap grid from array with map in reactjs

After fetching data from the backend. 从后端获取数据之后。 I want to render data in bootstrap grid but in reactjs if you open an element for example () you cannot wait until 3 occurences to close the div. 我想在引导网格中呈现数据,但是在reactjs中,如果您打开例如()的元素,您将等不到3次出现以关闭div。 This is a code sample about my problem 这是关于我的问题的代码示例

export default class Posts extends Component {
    state = {
        posts: []
    }

    componentDidMount() {
        fetch(`https://jsonplaceholder.typicode.com/posts`)
            .then(response => response.json())
            .then(json => {
                this.setState({ posts: json })
            })
    }

    renderPosts() {
        const { posts } = this.state;

        if (posts.length > 0) {

            posts.map((post, index) => {

                // This is my issue here

                if (index === 0) {

                    return (<div className="row">

                        <div> className="col-sm">{post.title} </div>)

                } else if (index % 5 === 0) {


                    return (</div className="row">
                        <div className="row">
                        <div> className="col-sm">{post.title} </div>)

                } else {
                    return (<div> className="col-sm">{post.title} </div>)
                }

            })

        } else {
            return null;
        }
    }

    render() {
        return (
            <div>{this.renderPosts()}</div>
        )
    }
}

I solved this problem by grouping my data into an array of arrays. 我通过将数据分组为一个数组来解决了这个问题。 The array represents the rows. 数组代表行。 and inside of it arrays that represents the columns. 在它里面的数组代表列。

const RowPostGroups = [];
            for (let i = 0; i < photos.length; i = i + 5)
                RowPostGroups.push(photos.slice(i, i + 5));
// then map for rows
// then map for columns

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM