反应状态无缘无故神奇地改变

时间:2018-05-14 08:45:38

标签: javascript reactjs api momentjs fetch-api

我正在使用React作为日历应用程序。我从API获取某些日期的数据,一次只从数据库中获取1周的数据。

当我从这样的API获取时:

export default class CalendarApp extends React.Component {
  state = {
    months: moment.months(),
    day: moment.weekdays(),
    daysPerMonth: moment().daysInMonth(),
    startDate: moment(),
    date: moment().year(2017).month(0).date(1).format('l'),
    firstWeekDay: 0,
    data: [],
    minDate: moment().year(2017).month(0).date(1),
    maxDate: moment().year(2018).month(11).date(31)
  };
  componentDidMount() {


    const startDate = this.state.startDate.day(this.state.firstWeekDay).unix();
    const endDate = this.state.startDate.day(this.state.firstWeekDay).add(1, 'week').unix();
    console.log(`I am fetching data between ${moment.unix(startDate).format("MM/DD/YYYY")} and ${moment.unix(endDate).format("MM/DD/YYYY")}`);

    // console.log(this.state.startDate.day(this.state.firstWeekDay));

    axios.get(`http://localhost/api/date?startDate=${startDate}&endDate=${endDate}`).then((response) => {
      this.setState(() => ({ data: response.data}));
    });
  };

然后startDate神奇地改变(它就像我在endDate变量上加了1周,即使我从来没有使用过setState)。 结果我的日历应用程序被破坏了,它总是在我需要之前一周而不是本周。 例如,如果我的日历显示的时间是05/20/2018和05/26/2018之间的天数,那么我会在2015年5月15日到2015年5月20日之间从API获取数据。

2 个答案:

答案 0 :(得分:0)

您正在更改componentDidMount中的状态,因此会更新。在进行任何更改之前,使用时刻对象上的.clone()方法克隆它

componentDidMount() {
    let startDate = 
this.state.startDate.clone()
    startDate = startDate.day(this.state.firstWeekDay).unix();
    const endDate = this.state.startDate.clone().day(this.state.firstWeekDay).add(1, 'week').unix();
    console.log(`I am fetching data between ${moment.unix(startDate).format("MM/DD/YYYY")} and ${moment.unix(endDate).format("MM/DD/YYYY")}`);

    // console.log(this.state.startDate.day(this.state.firstWeekDay));

    axios.get(`http://localhost/api/date?startDate=${startDate}&endDate=${endDate}`).then((response) => {
      this.setState(() => ({ data: response.data}));
    });
  };

答案 1 :(得分:0)

我从未使用过时刻,但我在文档中发现了这一点:

  

注意:应该注意的是,时刻是可变的。调用任何操作方法都会改变原始时刻。

https://momentjs.com/docs/#/manipulating/

所以当你打电话时

this.state.startDate.day(this.state.firstWeekDay).add(1, 'week').unix();

它会更改您的开始日期并将其返回。

希望它对你有所帮助。