为什么useState中的初始状态值未定义?

时间:2020-05-08 03:52:50

标签: reactjs react-hooks

在以下代码中。我使用一个函数来获取状态变量的初始值。但是,当我为控制台登录代码编写函数时以及运行该函数(b和c)后,未设置nextAppointment状态。救命!

我添加了使用相同功能正确设置的随机变量Cow,以表明我的源数据还可以。

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>);
}

更新:在find方法中将a => a.AppointmentDateTime > currentTime更改为a => a.AppointmentDateTime.isAfter(currentTime),但没有得到肯定的结果。

1 个答案:

答案 0 :(得分:0)

我在共享代码中没有看到任何问题,但是我可以指出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 );

.parent {
  height: 150px;
  width: 150px;
  background-color: red;
}

.subNavigator {
  padding: 10px;
  height: 100px;
  width: 100px;
  background-color: blue;
}

.parent:hover .subNavigator {
  background-color: green;
}

让我知道这是否有帮助!