簡體   English   中英

如何將經典 reactjs 轉換為掛鈎?

[英]how do I convert classic reactjs to hooks?

我試圖將以下內容轉換為鈎子,但是我遇到了一些問題來翻譯這一行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 的官方指南向您推薦 go ,指南末尾有一個完整的示例,說明如何使用 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/

const fetchPlaces = (q) => {
    get(`http://www.example.com/places/`, {
        params: {q}
    }).then(response => {
        setPlaces(response.data.places);
    });
}

const deboucedFetchPlaces = debounce(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();


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM