我正在尝试将此文件 https://github.com/wix/react-native-calendars/blob/7aefe01f0e18df4272ae0d1d9990af196e30cc17/example/src/screens/agenda.js#L8 更改为钩子,但我很难弄清楚使setItems对函数loadItems可见这就是我到目前为止尝试做的事情 https://pastebin.com/JSzbJLqV
我有我的州const [items, setItems] = useState({});
我想让它对这个函数可见const loadItems = (天( => { ...
我收到此错误:引用错误:找不到变量项
问题 :
loadItems
函数在const Calendar = () => {
之外,items
变量作用域仅在该函数内,而不是在该函数之外,并且您正在尝试从外部函数访问它。
const Calendar = () => {
const [items, setItems] = useState({});
...
}
const loadItems = (day) => {
....
// you are trying to access `items` inside it
if (!items[strTime]) {
...
}
溶液:
const Calendar = () => {
const [items, setItems] = useState({});
// put it inside the functional component
const loadItems = (day) => {
....
}
}
钩子中的状态可用于它定义的函数! 使 loadItems 函数作为日历函数本身中的辅助函数,然后您也可以将状态 [items, setItems] 用于 loadItems 函数
喜欢这个:
const Calendar = () => {
const [items, setItems] = useState({});
const loadItems = day => {
setTimeout(() => {
for (let i = -15; i < 85; i++) {
const time = day.timestamp + i * 24 * 60 * 60 * 1000;
const strTime = timeToString(time);
if (!items[strTime]) {
items[strTime] = [];
const numItems = Math.floor(Math.random() * 3 + 1);
for (let j = 0; j < numItems; j++) {
items[strTime].push({
name: "Item for " + strTime + " #" + j,
height: Math.max(50, Math.floor(Math.random() * 150))
});
}
}
}
const newItems = {};
Object.keys(items).forEach(key => {
newItems[key] = items[key];
});
setItems(newItems);
}, 1000);
};
return (
<div
items={items}
loadItemsForMonth={loadItems}
selected={"2020-05-16"}
rowHasChanged={rowHasChanged}
/>
);
};
我希望这有所帮助。