[英]window.location.href with React.js
我需要帮助。
如果我使用 JSON.stringify(window.location.href),有没有办法显示 URL 没有“”(引号/作为字符串)? 所以将其显示为链接而不是字符串。
如果不是...有没有办法在 React 中使用 window.location.href 而不必使用 JSON.stringify()?
或者也许使用一些东西来替换 window.location.href 但结果相同?
基本上需要显示/使用 url 作为链接(html <a> 标签)而不是字符串。
新图像!
--- 忽略密钥:URL_HREF 而不是 MY_URL ---
任何帮助表示赞赏!
这似乎可以满足您的要求。
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>
编辑:但我也很好奇为什么<a href={window.location.href}> Link </a>
不起作用。
问题似乎出在您的自定义挂钩上。 这是一个应该起作用的变体:
如果您没有在 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.