在React JS State中推送/更新数组

时间:2017-11-28 11:44:38

标签: javascript reactjs

我在使用React JS方面相当陌生,而且在将项目推送到组件状态的一部分数组时遇到了问题。

我打算发生的事情是当组件安装状态(allDays数组)更新为当前月份和接下来的两个月中的每一天。我只是得到一个空阵列。我已经检查了循环并输出了日期,但它们并没有被推送到数组。

我目前的JavaScript是:

class CalendarDisplay extends React.Component {

    constructor(props) {
        super(props);
        this.state = { allDays: [] };
    }

    findDays = () => {

        var self = this;

        var currentDate = new Date();
        var mFormat = currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-01';

        var startBookingDate = moment(mFormat);
        var endBookingDate = moment().add(2, 'M').endOf('month');

        var currentDate = moment(startBookingDate);

        while (currentDate <= endBookingDate) {

            self.setState({
                allDays: self.state.allDays.concat(moment(currentDate).format('YYYY-MM-DD'))
            });

            currentDate = moment(currentDate).add(1, 'days');

        }

    }

    componentDidMount = () => {

        this.findDays();
        console.log(this.state.allDays);

    }

    render = () => {
        return (
            <div>Please See the Console Log</div>
        )
    }

}

ReactDOM.render(
  <CalendarDisplay />,
  document.getElementById('app')
);

这是问题的JS Fiddle

我一直在阅读Stack Overflow上的其他答案,他们似乎无法解决此问题。我目前正试图使用​​concat技术而没有成功。

任何帮助都会很棒。

3 个答案:

答案 0 :(得分:3)

性能方面,更新状态太多次并不是一个好的模式。更不用说它会触发render很多。

我的建议是将所有值保存在临时变量中,然后只更新一次状态。

let days = []
while (currentDate <= endBookingDate) {
   days = [...days, moment(currentDate).format('YYYY-MM-DD')]
   currentDate = moment(currentDate).add(1, 'days')
}

this.setState({ allDays: days })

答案 1 :(得分:0)

更改

self.setState({
                allDays: self.state.allDays.concat(moment(currentDate).format('YYYY-MM-DD'))
            });

To(根据评论编辑)

 self.state.allDays.push(moment(currentDate).format('YYYY-MM-DD'));

你需要将值推送到数组而不是连接它们。

请参阅JsFiddle

答案 2 :(得分:0)

我很确定你不能像这样更新状态。您应该完全构建结束数组,然后更新状态。这样做的另一个好处是你只会更新一次状态(而不是30/31次)。

findDays = () => {
    var month = [];
    var self = this;

    var currentDate = new Date();
    var mFormat = currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-01';

    var startBookingDate = moment(mFormat);
    var endBookingDate = moment().add(2, 'M').endOf('month');

    var currentDate = moment(startBookingDate);

    while (currentDate <= endBookingDate) {

        month.push(moment(currentDate).format('YYYY-MM-DD'));

        currentDate = moment(currentDate).add(1, 'days');

    }

    self.setState({ allDays: month );

}