以链接代替测试,一段 js 前端调试的代码

任意修改/设定 页面状态变量,仅在调试的模式下生效。

利用页面链接中的参数来判定所决定的状态和其值,以决定相应的初值或初始条件。

React 代码如下,定义 hooks/dev_helpers/loc.js useQueryPreset

// hooks/dev_helpers/loc.js
import React from 'react';

export const useQueryPreset = ({ k, onMatch, deps = [] }) => {
  let match = React.useRef(null);
  let v = React.useRef(null);

  React.useEffect(() => {
    match.current = window.location.href.match(new RegExp(`[?&]${k}=?([^&^#]*)`), 'i');
    if (match.current) {
      console.log('[%s] href:%s; matchArr:%o', k, window.location.href, match.current);
      v.current = match.current[1];
      if (onMatch) {
        onMatch(v.current);
      }
    }
  }, deps);

  return {
    match,
    v,
  }
}

用法示例

  useQueryPreset({
    k: 'preset_num_pages', onMatch: (v) => {
      console.log('[useQueryPreset] numPages:%s', numPages);
      if (numPages > 1) {
        let _numPages = Number(v);
        console.log('[useQueryPreset:call:setPage] _numPages:%s', _numPages);
        setNumPages(_numPages);
      }
    }, deps: [numPages]
  });

访问页面 test?preset_num_pages=0

本文定义了一段 useQueryPreset 的 React hooks 代码,用于开发(页面状态),谢谢阅读。

关于本文如您有任何想法和意见,欢迎与我们联系,邮箱地址zhi@uqugu.com
您对本文有什么看法,喜欢或者不喜欢都可以发表意见。