【问题标题】:React state magically changes for no reasonReact 状态无缘无故地神奇地改变
【发布时间】:2018-10-23 20:59:45
【问题描述】:

我正在将 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 神奇地改变(它增加了 1 周,就像我在 endDate 变量上一样,即使我从未为此使用 setState)。 结果我的日历应用程序坏了,它总是在我需要之前一周而不是当前周。 例如,如果我的日历显示 2018 年 5 月 20 日到 2018 年 5 月 26 日之间的日子,我会从 API 获取 2018 年 5 月 13 日到 2018 年 5 月 20 日之间的数据。

【问题讨论】:

    标签: javascript reactjs api momentjs fetch-api


    【解决方案1】:

    您正在直接改变 componentDidMount 中的状态,因此它会被更新。在进行任何更改之前,对 moment 对象使用 .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}));
        });
      };
    

    【讨论】:

    • 它可以让我克隆 startDate,但是当我在 endDate 变量中使用 startDate.clone() 时会抛出错误:“startDate.clone 不是函数”。
    • 从状态中使用 startDate,因为克隆不适用于 unix 值
    • 是的,谢谢我已经这样做了。我现在可以工作了,谢谢!
    • 很高兴能帮上忙
    【解决方案2】:

    我从未使用过 moment,但我在文档中找到了这个:

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

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

    所以当你打电话时

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

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

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-02
      • 2010-12-24
      • 2011-08-05
      • 2020-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多