首页 > 解决方案 > 如何将经典的 reactjs 转换为钩子?

问题描述

我试图将以下内容转换为钩子,但是我遇到了一些问题来翻译这一行this.fetchPlaces = debounce(this.fetchPlaces, 200); ,钩子的确切匹配是什么?

state = {
    q: '',
    places: [],
}
fetchPlaces(q) {
    get(`http://www.example.com/places/`, {
        params: {q}
    }).then(response => {
        this.setState({places: response.data.places});
    });
}
constructor(props) {
    super(props);
    this.fetchPlaces = debounce(this.fetchPlaces, 200);
}```

标签: javascriptreactjs

解决方案


我建议你阅读 React Hooks 的官方指南,在指南的最后有一个完整的例子来说明如何使用 React Hooks。

您应该使用 useState 挂钩来管理状态并使用 useEffect 挂钩从网络加载数据。

const Foo = () =>{
   // all hooks should be used in top level of the function component.
   // orders matter.
   // https://www.reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
   const [q, setQ] = useState(''); // use hooks to declare q
   const [places, setPlaces] = useState([]); // use hooks to declare places

   // load data from network after React Nodes are rendered
   useEffect(()=>{
      get(`http://www.example.com/places/`, {
        params: {q}
      }).then(response => {
        setPlaces(response.data.places); // call setPlaces to set state
      });
   }
   ,[1]);  // passing a constant to the second Array parameter to strict the hook be called only for once, if left undefined, useEffect will be called after every render.
   return // React Nodes
}

我已经使用了一段时间的反应钩子,你可以在这里查看我的完整示例。 https://github.com/ShinChven/bootcamp/blob/master/console/src/pages/Admin/Users/Users.tsx

我不明白为什么你应该用 debounce 调用网络,但这里有一个帖子。 https://www.freecodecamp.org/news/debounce-and-throttle-in-react-with-hooks/


推荐阅读