如何在状态内渲染组件?

时间:2016-09-16 20:12:52

标签: javascript reactjs

我正在学习反应,我一直坚持如何在我的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'));

2 个答案:

答案 0 :(得分:1)

试试这个:

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

然后在渲染函数上方创建一个名为renderBirthdays的函数,如下所示:

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

因此,您可以利用javascripts map来获取您的对象并锁定它们。然后我们将把这个键传递给一个名为renderBirthdays的函数,该函数将迭代该项。我们需要将一个键和一个索引传递给元素,为了便于使用,我们可以将一个细节道具传递给它,它等于它迭代的当前所选项目。这样我们就可以在元素中使用{details.name}等。

答案 1 :(得分:0)

这是未经测试的,但这样的事情应该有效。使用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>
    );
}