当前位置:   article > 正文

自定义Hook-useSearchParam_阿里云

阿里云

效果图在这里插入图片描述

useSearchParam

import { useState, useEffect, useCallback } from 'react'

/**
 * 跟踪浏览器的位置搜索参数。
 * @param {string} useSearchParam 传递参数 search 名称
 * @return {string} useSearchParam 相应 search 值
 */
const useSearchParam = param =>
{
    const getValue = useCallback(
        () => new URLSearchParams(window.location.search).get(param),
        [param]
    );
    const [value, setValue] = useState(getValue);
    useEffect(() =>
    {
        const onChange = () =>
        {
            setValue(getValue());
        };

        window.addEventListener('popstate', onChange);
        window.addEventListener('pushstate', onChange);
        window.addEventListener('replacestate', onChange);

        return () =>
        {
            window.removeEventListener('popstate', onChange);
            window.removeEventListener('pushstate', onChange);
            window.removeEventListener('replacestate', onChange);
        };
    }, []);

    return value;
};

export default useSearchParam
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

index

import useSearchParam from './useSearchParam '

const params = {
    name: 'name',
    age: 'age',
    sex: 'sex'
}
const index = () =>
{
    const paramName = useSearchParam(params.name);
    const paramAge = useSearchParam(params.age);
    const paramSex = useSearchParam(params.sex);
    return (
        <div>
            <p>参数值: {paramName || 'null'}  {paramAge || 'null'}  {paramSex || 'null'}</p>
            <button
                onClick={() => history.pushState({}, '', location.pathname + `?${params.name}=二弟&${params.age}=${17}&${params.sex}=${'女'}`)} >
                查看
            </button>
            <button onClick={() => history.pushState({}, '', location.pathname)}>
                退出
            </button>
        </div>
    );
};
export default index
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/335057
推荐阅读
相关标签
  

闽ICP备14008679号