如何将此文件从类更改为钩子?

时间:2020-06-14 03:26:18

标签: reactjs react-native react-hooks

我正在尝试将此文件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 =(day)=> {...

我遇到此错误: ReferenceError:找不到可变项

2 个答案:

答案 0 :(得分:1)

问题:

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) => {
       ....
    }

}

答案 1 :(得分:1)

挂钩中的

状态可以用于定义它的功能!在Calendar函数本身内部将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}
    />
  );
};

我希望这会有所帮助。