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
166 views
in Technique[技术] by (71.8m points)

javascript - ReactJS assign values dynamic 2D array in componentWillMount

I have some restaurants. Each of them have reviews. I want to store these reviews in a state. 2D array: each line represents a restaurant, and each element represents a review object.

It is necessary to do this operation in componentWillMount() due to the nature of the backend.

async componentWillMount() {
    let reviewsHelper = this.state.reviews.slice();
    for (var i = 0; i < restaurantCount; i = i + 1) {
        ...
            for (var j = 0; j < restaurant.reviewCount; j = j + 1) {
                ... get reviewObj
                reviewsHelper[i][j] = reviewObj
            }
    }
    this.setState({
        reviews: reviewsHelper
    })
}

...

constructor(props) {
    super(props)
    this.state = {
        reviews: [[], [], [], []],
        ...
    }
}

This works. However, as you might have seen, when I define the state in the constructor, I have 4 []. That means I support 4 restaurants.

How do I change this so I accept infinite restaurants? or, even better, a number of restaurantCount restaurants?

I am a total newbie in React, any help would be greatly appreciated.

question from:https://stackoverflow.com/questions/65873773/reactjs-assign-values-dynamic-2d-array-in-componentwillmount

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

1 Reply

0 votes
by (71.8m points)

I eventually fixed it after scouring Google for hours.

async componentWillMount() {
    let reviewsHelper = this.state.reviews.slice();
    for (var i = 0; i < restaurantCount; i = i + 1) {
        ...
        var helperList = []
        for (var j = 0; j < restaurant.reviewCount; j = j + 1) {
            ... get reviewObj
            helperList.push(reviewObj)
        }
        reviewsHelper.push(helperList)
    }
    this.setState({
        reviews: reviewsHelper
    })
}
constructor(props) {
    super(props)
    this.state = {
        reviews: [],
        ...
    }
}

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

...