javascript - 如何将经典的 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);
}```
解决方案
我建议你阅读 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/
推荐阅读
- javascript - React Hook 中的条件语句问题
- javascript - 如何将 HTML 标签内容传递给 mark.js 并用空格或逗号分隔它们?
- reactjs - 写东西时页面跳转
- java - 无法使用 FragmentContainerView 运行 Robolectric 和 Espresso
- java - 我想使用泛型制作数组
- android - 调用完成()时销毁活动后会发生什么?
- html - 表格行编辑功能在角度不起作用
- html - Bootstrap-select 未显示在我的网站上
- python-3.x - Flask,SQLAlchemy,无法将集合与对象或集合进行比较;使用 contains() 来测试成员资格
- android - 如何使用 kotlin 从 firebase 检索 pdf 文件?