代码之家  ›  专栏  ›  技术社区  ›  yudhiesh

使用异步操作发出API请求的useReducer

  •  0
  • yudhiesh  · 技术社区  · 4 年前

    description 当一个按钮 query 单击它将执行 POST 请求,然后在字段中发送文本 在请求的正文中。

    查询 按钮。

    Action for querying the data(I am not sure what to return in this case)

    switch (action.type) {
      case "query": {
        return {
          ...state,
        };
      }
    }
    

    Making the POST request and setting the JSON data in state which is then displayed(Takes as input the data from the field description)

    const fetchData = async (desc) => {
      const response = await fetch("/rank", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ terms: desc }),
      }).catch((e) => console.log(e));
      const dataJSON = await response.json().catch((e) => console.log(e));
      if (response.ok) {
        console.log("OK");
      }
      if (!response.ok) {
        const error = (dataJSON && dataJSON.message) || response.status;
        return Promise.reject(error);
      }
      setData(dataJSON.data);
    };
    
    useEffect(() => {
      fetchData(description);
    }, [description]);
    

    Button for making the query

    <Button
      type="button"
      onClick={() => {
        dispatch({ type: "query" });
      }}
    >
    

    useEffect 钩子被触发,即使我没有点击按钮查询,因为我不知道如何设置它的行动。

    1 回复  |  直到 4 年前
        1
  •  1
  •   buzatto    4 年前

    我认为没有必要使用effect来获取数据。您只希望在提交时调用该函数,而不是在每次状态更新时调用。

    setData . 一旦使用useReducer,这将导致重复状态。我建议删除这些数据 state 如果你用的是减速机。

    const fetchData = async () => {
      try {
      const response = await fetch("/rank", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ terms: description }),
      })
      const dataJSON = await response.json();
      if (response.ok) {
        console.log("OK");
      }
      if (!response.ok) {
        const error = (dataJSON && dataJSON.message) || response.status;
        throw error;
      }
      dispatch({ type: "query", data: dataJSON.data });
      } catch (error) {
        console.log(error)
      }
    };
    

    switch (action.type) {
      case "query":
        return {...state, action.data };
      default:
        return state;
    }
    

    您还可以添加一些额外的分派操作,如 loading , success error 如果需要的话处理这些案子。