简体   繁体   English

window.location.href 与 React.js

[英]window.location.href with React.js

I need help.我需要帮助。

If I use JSON.stringify(window.location.href), is there any way to show that URL without "" (quotes / as a string)?如果我使用 JSON.stringify(window.location.href),有没有办法显示 URL 没有“”(引号/作为字符串)? So showing it like a link and not a string.所以将其显示为链接而不是字符串。

If not... Is there a way to use window.location.href in React without having to use JSON.stringify()?如果不是...有没有办法在 React 中使用 window.location.href 而不必使用 JSON.stringify()?

Or maybe use something to replace window.location.href but same result?或者也许使用一些东西来替换 window.location.href 但结果相同?

Basically need to show / use that url as a link (html < a > tag) not as a string.基本上需要显示/使用 url 作为链接(html <a> 标签)而不是字符串。

New images!新图像!

code代码

useStickyState function使用StickyState function

--- Ignore the key: URL_HREF its MY_URL instead --- --- 忽略密钥:URL_HREF 而不是 MY_URL ---

with JSON.stringify与 JSON.stringify

without JSON.stringify没有 JSON.stringify

Any help is appreciated!任何帮助表示赞赏!

This seems to do what you're asking.这似乎可以满足您的要求。

 class SimpleExample extends React.Component { render() { return ( <div> <a href={`${window.location.href}`}> Link </a> </div> ); } } ReactDOM.render(<SimpleExample />, document.getElementById('example'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.2/umd/react-dom.production.min.js"></script> <div id="example"></div>

EDIT: But I'm also curious why <a href={window.location.href}> Link </a> doesn't work.编辑:但我也很好奇为什么<a href={window.location.href}> Link </a>不起作用。

The problem seems to be with your custom hook.问题似乎出在您的自定义挂钩上。 Here's a variation that should work:这是一个应该起作用的变体:

TypeScript Playground link TypeScript 游乐场链接

If you aren't using or can't use TypeScript in your React project, you can navigate to the playground link above and copy the transpiled JavaScript code (it's on the right side of the page).如果您没有在 React 项目中使用或不能使用 TypeScript,您可以导航到上面的 playground 链接并复制转换后的 JavaScript 代码(它位于页面右侧)。

import {
  default as React,
  useCallback,
  useEffect,
  useState,
  type Dispatch,
  type SetStateAction,
} from 'react';

// useLSState: This is a modified version of your "useStickyState"

export type Result <T = void, E extends Error = Error> = T | E;

export function getError (exception: unknown): Error {
  return exception instanceof Error ? exception : new Error(String(exception));
}

export type Json = boolean | null | number | string | Json[] | { [key: string]: Json };
export type JsonValidator = (data: Json) => boolean;

export function safeParse <T extends Json = Json>(json: string, validate: JsonValidator = () => true): Result<T> {
  try {
    const data = JSON.parse(json) as T;
    if (validate(data)) return data;
    throw new Error('Parsed JSON failed validation');
  }
  catch (ex) { return getError(ex); }
}

export function safeLSGet <T extends Json = Json>(key: string, validate: JsonValidator = () => true): Result<T> {
  const json = localStorage.getItem(key) ?? new Error(`localStorage item at "${key}" was null`);
  return json instanceof Error ? json : safeParse(json, validate);
}

export function safeLSSet <T extends Json = Json>(key: string, value: T): Result {
  try {
    const json = JSON.stringify(value);
    localStorage.setItem(key, json);
  }
  catch (ex) { return getError(ex); }
}

export function useLSState <T extends Json>(
  initalState: T,
  key: string,
  validate?: JsonValidator,
): [state: T, setState: Dispatch<SetStateAction<T>>] {
  const [value, setValue] = useState(initalState);

  useEffect(() => {
    const parsed = safeLSGet<T>(key, validate);
    if (parsed instanceof Error) {/* the localStorage value was null */}
    else setValue(parsed);
  }, [key, validate]);

  const setLSValue = useCallback<Dispatch<SetStateAction<T>>>(action => {
    if (typeof action === 'function') {
      setValue(prev => {
        const value = action(prev);
        const err = safeLSSet(key, value); // potentially useful for debugging
        return value;
      });
      return;
    }

    const value = action;
    setValue(value);
    const err = safeLSSet(key, value); // potentially useful for debugging
  }, [key, setValue]);

  return [value, setLSValue];
}


// Example usage:

const lsKey = 'MY_URL';

function Example (props: { item_url: string }) {
  const [previouslyClickedUrl, setPreviouslyClickedUrl] = useLSState(window.location.href, lsKey);

  const handleClick: React.MouseEventHandler<HTMLAnchorElement> = ev => {
    // Prevent native navigation on click
    ev.preventDefault();

    // Update the localStorage item
    setPreviouslyClickedUrl(window.location.href);

    // Navigate to the new URL
    window.location.href = props.item_url;
  };

  return (
    <div>
      <div>Previous URL: {previouslyClickedUrl}</div>
      <a
        href={props.item_url}
        onClick={handleClick}
      >{props.item_url}</a>
    </div>
  );
}

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

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