首页 > 解决方案 > 为什么我在 useState 中的初始状态值未定义?

问题描述

在下面的代码中。我使用一个函数来获取状态变量的初始值。但是,当我在函数中为控制台登录编写代码并且在函数运行后(b 和 c),nextAppointment 状态没有被设置。帮助!

我添加了一个使用相同函数正确设置的随机变量牛,以表明我的源数据没问题。

const getNextAppointment = appointments => {
  let currentTime = moment();
  let nextAppt = appointments.find(a => a.AppointmentDateTime > currentTime);
  console.log('B', nextAppt);
  return nextAppt;
};

function AppointmentListByDate(props) {
  let appointments = props.appointments.sort((a, b) => a.AppointmentDateTime - b.AppointmentDateTime);
  console.log('A');
  var [nextAppointment, setNextAppointment] = React.useState(getNextAppointment(appointments));
  console.log('C', nextAppointment);
  var cow = getNextAppointment(appointments);
  console.log('D', cow);
  render(<div>Hello World</div>);
}

更新:在没有积极结果的情况下更改a => a.AppointmentDateTime > currentTime为find 方法。a => a.AppointmentDateTime.isAfter(currentTime)

标签: reactjsreact-hooks

解决方案


我在共享代码中看不到任何问题,但我可以指出 1 个可能给您带来问题的区域。

我猜它moment()返回一个日期对象。我不确定你的约会格式是什么props,所以如果你可以分享这些细节,那么我可能可以分享整个代码或者只是试一试,它不应该那么复杂。

我创建了一个没有 的演示moment,效果很好。

https://codesandbox.io/s/serene-davinci-quxz1?fontsize=14&hidenavigation=1&theme=dark

也不要直接将函数放入useState,试试这个

  const initialNextAppointment = getNextAppointment(appointments);
  var [nextAppointment, setNextAppointment] = React.useState(
    initialNextAppointment
  );

让我知道这是否有帮助!


推荐阅读