我正在尝试为我的 React 图像搜索应用程序实现搜索参数功能。而且,我了解到我需要(可以)使用 useSearchParams Hook,但我不确定如何进行这些更改。
所以,基本上我希望 URL 类似于 localhost:3000/ input&page=1,这意味着斜杠后面的任何内容都将是input页码的值和键/值对。
正如您在 app.js 中看到的,我有这 3 个主要路由,而主路由(呈现 Main.js)是我主要处理的路由。此外,Main.js 渲染 Header.js(渲染表单和其他)。
我想我应该在 app.js 中创建一个新的路线,但我不知道该怎么做。
import './App.css';
import Home from './components/pages/Home';
import Favorites from './components/pages/Favorites';
import Error from './components/pages/Error';
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { SkeletonTheme } from 'react-loading-skeleton';
import { useDarkMode } from './components/Navbar';
function App() {
const darkMode = useDarkMode(state => state.darkMode)
let style
if (darkMode === 'light') {
style = 'wrapper'
} else { …Run Code Online (Sandbox Code Playgroud) query-string reactjs react-router react-hooks urlsearchparams
从我的理智后端提取数据时,我的反应本机项目出现错误\xc2\xa0\n\xc2\xa0\n这是错误\nURLSearchParams.set is not implemented
这是我获取 data\xc2\xa0 的地方
\nimport {View, Text,SafeAreaView,Image,TextInput,ScrollView} from 'react-native'\nimport React, {useEffect, useLayoutEffect, useState} from 'react'\nimport {useNavigation} from "@react-navigation/native";\nimport {ChevronDownIcon, UserIcon,AdjustmentsVerticalIcon,MagnifyingGlassIcon} from "react-native-heroicons/outline";\nimport Categories from "../components/Categories";\nimport FeaturedRow from "../components/FeaturedRow";\nimport client from "../sanity";\n\nconst HomeScreen = () => {\n const navigation = useNavigation();\n const [featuredItems, setFeaturedItems] = useState([]);\n\n useLayoutEffect(()=>{\n navigation.setOptions({\n headerShown: false,\n });\n },[]);\n\n useEffect(()=>{\n const query = `*[_type == "featured"]`;\n\n client\n .fetch(query)\n .then((data)=>{\n setFeaturedItems(data)\n })\n .catch((error)=>{\n console.log('Error:',error);\n });\n }, []);\nRun Code Online (Sandbox Code Playgroud)\n这也是我的 Sanity.js 代码
\nimport …Run Code Online (Sandbox Code Playgroud) 有一个小组件,当您单击按钮时,URL 中的搜索参数会发生变化。但是当搜索参数更改时,整个组件都会重新渲染,是否可以只更改 url,而不重新渲染?或者也许在这里使用“use-query-params”并不是一个好主意?
import React from 'react';
import { StringParam, useQueryParam } from 'use-query-params';
import cl from './Footer.module.scss';
const Footer = () => {
const [tab, setTab] = useQueryParam('ptab', StringParam);
const handleClick = e => setTab(e.target.name);
const getClass = name => {
const values = ['tab1', 'tab2', 'tab3'];
if (tab === name || (name === 'tab4' && (!tab || !values.includes(tab)))) return cl.active;
return '';
};
return (
<ul className={cl.footer}>
<li>
<button name='tab1' onClick={handleClick} className={getClass('tab1')}>
Tab1
</button>
</li>
<li>
<button name='tab2' …Run Code Online (Sandbox Code Playgroud) 我有一个通过参数接收对象的函数,该对象进入 URLSearchParams 内部,在此之后,我创建一个 toString() 并得到以下答案:
const object = {
name: 'Test',
age: 20
};
function exampleFunction(objectExample) {
const url = new URLSearchParams(objectExample);
return url.toString();
};
console.log(exampleFunction(object));
// result: name=Test&age=20
Run Code Online (Sandbox Code Playgroud)
答案结果是我所期望的,问题是当我尝试输入此参数创建一个接口时,例如:
interface ObjectTest { name: string, age: number }
function exampleFunction(objectExample: ObjectTest) {
const url = new URLSearchParams(objectExample: ObjectTest) << /* error, URLSearchParams expect a type Record<string, string> */;
return url.toString();
};
Run Code Online (Sandbox Code Playgroud)
无需输入,代码就可以正常工作,我的问题是:如果我的 URLSearchParams 期望其他东西,我如何输入此参数来接收对象?我已经尝试传递一个对象 stringfy (如 JSON.stringfy(object) ,但结果类似于 // %7B%22ma,e%22%3A%22Test%22%2C%22age%age%22#A@) %70= 而不是 name=Test&age=20 )
我尝试了这两个选项,但没有任何运气:
let url = new URL(window.location.href);
let key = undefined;
for (let k of url.searchParams) {
if(url.searchParams[k] == postID) {
key = k;
}
}
Run Code Online (Sandbox Code Playgroud)
和
let url = new URL(window.location.href);
const filteredItems = Object.keys(url.searchParams).filter(key =>
url.searchParams[key] == postID
);
let key = filteredItems.keys.first;
Run Code Online (Sandbox Code Playgroud)
怎么了?
URLSearchParams.set(key, value) URI 对给定的值进行编码,产生丑陋的非指定 URL。
以下测试基于此 url 友好字符列表
const url = new URL("http://www.example.com/path");
const test = "abc123+-_$#%?@,"
url.searchParams.set("foo", test);
console.log(`What foo should be: ${test}`);
console.log(`What foo is: ${url.search}`)Run Code Online (Sandbox Code Playgroud)
有没有办法使用 URLSearchParams fromURL.searchParams将搜索参数更新为给定的值而不是其编码?
const url = new URLSearchParams('https://example.com?q1=1&q2=2');
console.log(url.has('q3')) // returns false as expected
console.log(url.has('q2')) // returns true as expected
console.log(url.has('q1')) // returns false as NOT expectedRun Code Online (Sandbox Code Playgroud)
为什么会发生这种情况?
javascript ×3
reactjs ×3
query-string ×2
fetch ×1
react-hooks ×1
react-native ×1
react-router ×1
sanity ×1
types ×1
typescript ×1
url ×1