简体   繁体   中英

How do I render components within a state in react?

I'm learning react and I'm stuck on how to render the birthdays within my this.state. I figured I would use something like:

 {this.state.birthdays}

but that doesn't seem to reach each birthday. My getElementByID is equal to a container which exists on my HTML. Any advice/help would be great!

    class App extends React.Component {
          constructor(props) {
            super(props);

            this.state = {
              birthdays: {
                'January': [{
                  name: 'Mike',
                  date: '1/14/90'
                }, {
                  name: 'Joe',
                  date: '1/7/92'
                }],

                March: [{
                  name: 'Mary',
                  date: '3/7/88'
                }]
              }
            }
          }

          render() {
            return ( 
              <div>

              </div>
            );
          }
        }
ReactDOM.render(<App />, 
document.getElementById('container'));

Try this:

{ Object.keys(this.state.birthdays).map(this.renderBirthdays) }

And then above your render function create a function called renderBirthdays like this:

renderBirthdays: function(key) {
    return (
         <div key={key} index={key} details={this.state.birthdays[key]}>
              {details.name} - {details.date}
         </div>
    )
},
render: function() {
    return (
        <div>{ Object.keys(this.state.birthdays).map(this.renderBirthdays) }</div>
    )
}

So you can take advantage of javascripts map which will take your object and key them. Then we're going to pass this key into a function called renderBirthdays which will iterate over the item. We need to pass a key and an index into the element, and for ease of use, we can pass a details prop into it equal to the currently selected item it's iterating over. That way we can just use {details.name} etc in the element.

This is untested, but something like this should work. Loop over the month keys using Object.keys , then reduce each set of birthdays to a flat array:

render() {
    return ( 
      <div>
        {Object.keys(this.state.birthdays).reduce((birthdays, month) => {
            return birthdays.concat(this.state.birthdays[month].map((bday) => {
                return (
                    <p>{bday.name} - {bday.date}</p>
                );
            }));
        }, [])}
      </div>
    );
}

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