reactjs - 为什么我在 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)
解决方案
我在共享代码中看不到任何问题,但我可以指出 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
);
让我知道这是否有帮助!
推荐阅读
- flutter - 如果用户在文本字段中输入值,如何更新文本小部件值
- java - onActivityResult 与 registerForActivityResult 有何不同?
- encoding - 将 US-ASCII 编码为 UTF-8 添加空格字符
- regex - 正则表达式:将 \r\n 作为普通单词处理
- typescript - 输入一个函数接收字符串数组并返回一个记录,每个字符串都有一个键
- webview - 如何使用 WebView 迁移代码以改用 WKWebview (macOS)?
- python - 从 www.kayak.it 抓取航班数据
- c - 字符串化函数返回值?
- firebase - 我如何获得标记的纬度和长度然后存储在火库中 - 颤动
- python - python编译器使用哪个级别的线程?内核线程或用户线程