我正在学习反应,并且坚持如何在this.state中渲染生日。我想我会用类似的东西:

 {this.state.birthdays}


但这似乎并没有达到每个生日。我的getElementByID等于我的HTML上存在的容器。任何建议/帮助都很好!

    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'));

最佳答案

这未经测试,但类似的东西应该起作用。使用Object.keys循环显示月份键,然后将每组生日减少为一个平面数组:

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>
    );
}

09-17 19:19