setState在React JS中不起作用

时间:2018-02-22 10:29:47

标签: reactjs

我想给state.periods数组提供几个日期。但它没有用。我的代码如下。

class SmallTable extends Component {
    constructor(props) {
        super(props);
        console.log(props.startDate)
        this.state = {
            turns: [],
            periods: []
        }
    }

componentDidMount() {
    //calculate years/ months and keep in one array
         const today = new Date();
         var periods1 = [];
         if (this.props.period=="year") { //if year calculate from last year last date
             const lastYearLastDate= new Date(new Date().getFullYear()-1, 11, 31)
             periods1.push(lastYearLastDate.getFullYear()+"-"+(lastYearLastDate.getMonth()+1)+"-"+lastYearLastDate.getDate());

             var lastYearFirstDate= new Date(lastYearLastDate.getFullYear()-1,0,1);

             //for the remaining periods
             for (var i=0;i<this.props.numberOfPeriods-1;i++) {
                 periods1.push(lastYearFirstDate.getFullYear()+"-"+(lastYearFirstDate.getMonth()+1)+"-"+lastYearFirstDate.getDate());
                 lastYearFirstDate = new Date(lastYearFirstDate.getFullYear()-1,0,1);
             }


         }


        else if (this.props.period=="month") {//if month calculate from last month last date
            var d=new Date(); // current date
            d.setDate(1); // going to 1st of the month
            d.setHours(-1); // going to last hour before this date even started.
            var lastMonthLastDate = d;
            periods1.push(lastMonthLastDate.getFullYear()+"-"+(lastMonthLastDate.getMonth()+1)+"-"+lastMonthLastDate.getDate());

            //go to last month  first date
            var lastMonthFirstDate = new Date(lastMonthLastDate.getFullYear(), lastMonthLastDate.getMonth(),1);

            //for the remaining periods
            for (var i=0;i<this.props.numberOfPeriods-1;i++) {
                periods1.push(lastMonthFirstDate.getFullYear()+"-"+(lastMonthFirstDate.getMonth()+1)+"-"+lastMonthFirstDate.getDate());

                lastMonthFirstDate=new Date(lastMonthFirstDate.getFullYear(), lastMonthFirstDate.getMonth()-1,1);
            }

        }

console.log(periods1); -->prints  ["2017-12-31", "2016-1-1", "2015-1-1", "2014-1-1"]
        this.setState((prevState)=>{
            return {
                periods: prevState.periods.push(periods1)
            }
        });
        console.log(this.state.periods) --> prints []

    }
render() {

        return ( <div></div>)
}

如何获取句点1到句点状态的值。我试图将periods1数组插入状态句点数组。这些是字符串。请提出错误的位置。

5 个答案:

答案 0 :(得分:2)

你有一些问题。

对于此处的代码:

Public Sub TestMe()

    ThisWorkbook.Date1904 = True
    Cells.Clear                                          'clearing up all.
    Dim cnt     As Long

    For cnt = 3 To 20
        Cells(1, cnt) = DateAdd("M", cnt, DateSerial(2016, 1, 1))
        Cells(1, cnt).NumberFormat = "MMM-YY"
    Next cnt

    Dim someDates(3)    As Date
    someDates(0) = DateSerial(2016, 1, 1)               'exists
    someDates(1) = DateSerial(2012, 1, 1)               'does not exist in the range
    someDates(2) = 5000                                 '08.09.1913 (in VBA)
    someDates(3) = 5                                    '04.01.1900 (in VBA)

    Dim foundRange      As Range
    For cnt = LBound(someDates) To UBound(someDates)
        Set foundRange = Rows(1).Find(someDates(cnt))   'Error 5 in Excel 2016
        If Not foundRange Is Nothing Then
            foundRange.Interior.Color = vbRed
        End If
    Next cnt

    ThisWorkbook.Date1904 = False                        'all dates with 4 years back

End Sub

你永远不想改变状态。相反,您应该创建一个新的数组对象,然后添加数据,如下所示:

return {
    periods: prevState.periods.push(periods1)
}

其次,你的console.log位于错误的地方

return {
    periods: prevState.periods.concat([periods1])
}

setState发生异步,因此在console.log(this.state.periods) --> prints [] 方法返回时可能无法完成。相反,将该console.log放在componentDidMount函数中以查看新状态。

答案 1 :(得分:1)

您将this.state.periods设置为push操作的结果。但是push返回新的数组长度,而不是数组本身。试试这个:

periods: [...prevState.periods, periods1]

答案 2 :(得分:1)

push()没有返回值。 你应该使用:

this.setState((prevState)=>{
    let old = prevState.periods.slice();
    old.push(periods1);
    return {
        periods: old
    }
});

答案 3 :(得分:1)

如果您希望this.state.periods是一个数组数组([["2017-12-31", "2016-1-1", "2015-1-1", "2014-1-1"]]),您可以使用spread operator按照不可变模式推送数组:

this.setState((prevState) => ({
       periods: [...prevState.periods, periods1]
    }), () => { console.log(this.state.periods) } );

您可以注意到,作为setState()的第二个参数传递的函数是在状态更新后执行console.log()的回调。

如果您想在periods1中推送this.state.periods ,可以执行以下操作:

this.setState((prevState) => ({
       periods: [...prevState.periods, ...periods1]
    }));

答案 4 :(得分:0)

尝试制作原始state的副本,以便您可以以不可变的方式执行setState

const periods = [...this.state.periods];
periods.push(periods1);
this.setState({periods: periods});