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

javascript - How to render a Object in React?

I want to render a Object .

My Object is:

const ObjectTest = {
        1: {
            id : 1,
            name:'ABC'
        },
        3: {
            id: 3,
            name:'DEF'
        }
}

I want it to render as:

id is 1 ; name is ABC
id is 3 ; name is DEF

I want to make this object in a function and is called in render function.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Data is an object so directly we can't use map on that, so use Object.keys or Object.entries to get the array first, then use map on that to create ui items.

Using Object.keys:

_renderObject(){
    return Object.keys(ObjectTest).map(obj, i) => {
        return (
            <div>
                id is: {ObjectTest[obj].id} ;
                name is: {ObjectTest[obj].name}
            </div>
        )
    })
}

Using Object.entries:

const ObjectTest = {
    1: {
        id : 1,
        name:'ABC'
    },
    3: {
        id: 3,
        name:'DEF'
    }
}

class App extends React.Component{

_renderObject(){
return Object.entries(ObjectTest).map(([key, value], i) => {
return (
<div key={key}>
id is: {value.id} ;
name is: {value.name}
</div>
)
})
}

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

ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

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

...