简体   繁体   中英

How can I display data with a loop in React?

I have the following code that works. However, there is a lot of repetition. Here is the code.

            <tr>
                <th>Brand</th>
                <td>{ a_data.brand }</td>
                <td>{ b_data.brand }</td>
                <td>{ c_data.brand }</td>
            </tr>

            <tr>
                <th>Model</th>
                <td>{ a_data.model }</td>
                <td>{ b_data.model }</td>
                <td>{ c_data.model }</td>
            </tr>

            <tr>
                <th>Variant</th>
                <td>{ a_data.variant }</td>
                <td>{ b_data.variant }</td>
                <td>{ c_data.variant }</td>
            </tr>

I have tried to create an array const data = ['a_data', 'b_data', 'c_data']; and loop through that to dynamically display the variables with forEach as well as map . But it does not display anything.

How can I put this in a loop?

There are many solution to your problem , one and easy solution is

    const a_data = {
    brand:'a',
    model:'aModel',
    variant:'aVariant'
}
const b_data = {
    brand:'b',
    model:'bModel',
    variant:'bVariant'
}
const c_data = {
    brand:'c',
    model:'cModel',
    variant:'cVariant'
}
const data = [a_data,b_data,c_data];
const brands = data.map(brand => (
    <td>{ brand.brand }</td>
));
const models = data.map(brand => (
    <td>{ brand.model }</td>
));
const variants = data.map(brand => (
    <td>{ brand.variant }</td>
));

<tr>
    <th>Brand</th>
    { brands }
</tr>

<tr>
    <th>Model</th>
    { models }
</tr>

<tr>
    <th>Variant</th>
    { variants }
</tr>

as you can see in this solution I use a mock for your objects and add this objects to the array called data .

This might be a tad verbose, but you can refactor it if you want. The gist is:

const data = [a_data, b_data, c_data];

const brands = data.map(brand => <td>{ brand.brand }</td>);
const models = data.map(brand => <td>{ brand.model }</td>);
const variants = data.map(brand => <td>{ brand.variant }</td>);

<tr>
    <th>Brand</th>
    { brands }
</tr>

<tr>
    <th>Model</th>
    { models }
</tr>

<tr>
    <th>Variant</th>
    { variants }
</tr>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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