简体   繁体   English

如何创建自定义反应钩子?

[英]How to create a custom react hook?

I have an addQuery function that sets the url with query parameters, like /hello/?page=1&role=admin etc. I want to use that function into multiple files for updating the URL and duplicating that function does not make sense. I have an addQuery function that sets the url with query parameters, like /hello/?page=1&role=admin etc. I want to use that function into multiple files for updating the URL and duplicating that function does not make sense.

export default function Hello() {
  const location = useLocation();
  const history = useHistory();

  const addQuery = (key, value) => {
    let pathname = location.pathname;
    let searchParams = new URLSearchParams(location.search);
    searchParams.set(key, value);
    history.push({
      pathname: pathname,
      search: searchParams.toString()
    });
  };

  return (
    <div>
      <h1>hello world</h1>
      <button onClick={() => addQuery("page", 1)}>page 1</button>
      <button onClick={() => addQuery("page", 2)}>page 2</button>
      <button onClick={() => addQuery("user_role", "admin")}>Admin role</button>
    </div>
  );
}

Is there a way to extract the logic into a separate hook?有没有办法将逻辑提取到单独的钩子中?

Here is the codesandbox link:https://codesandbox.io/s/add-query-hook-js2k7?file=/src/home.js这是代码框链接:https://codesandbox.io/s/add-query-hook-js2k7?file=/src/home.js

If you want to extract the addQuery function to a separate hook you have to return the desired function from the hook and call it when required.如果要将addQuery function 提取到单独的钩子中,则必须从钩子中返回所需的 function 并在需要时调用它。

Solution, in useAddQuery.js解决办法,在使用AddQuery.js

import { useLocation, useHistory } from "react-router-dom";
import { useCallback } from "react";

export function useAddQuery() {
  const location = useLocation();
  const history = useHistory();

  const addQuery = useCallback(
    (key, value) => {
      let pathname = location.pathname;
      let searchParams = new URLSearchParams(location.search);
      searchParams.set(key, value);
      history.push({
        pathname: pathname,
        search: searchParams.toString()
      });
    },
    [location, history]
  );

  return addQuery;
}

Working codesandbox example codesandbox工作代码和框示例代码和框

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM