Javascript 如何将经典reactjs转换为挂钩?
我试图将以下内容转换为hook,但是我在翻译这行代码时遇到了一些问题Javascript 如何将经典reactjs转换为挂钩?,javascript,reactjs,Javascript,Reactjs,我试图将以下内容转换为hook,但是我在翻译这行代码时遇到了一些问题this.fetchPlaces=debounce(this.fetchPlaces,200)钩子的精确匹配是什么 state = { q: '', places: [], } fetchPlaces(q) { get(`http://www.example.com/places/`, { params: {q} }).then(response => { t
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);
}```
然后在代码中可以调用deboucedFetchPlaces
您可以这样做
const fetchMore = _.debounce(fetchPlaces, 500);
fetchPlaces(q) {
get(`http://www.example.com/places/`, {
params: {q}
}).then(response => {
this.setState({places: response.data.places});
});
}
fetchMore();
我建议您仔细阅读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
}
我已经使用react钩子一段时间了,您可以在这里查看我的完整示例。
我不明白你为什么要打电话给网络与debounce,但这里有一个帖子。
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
}