gpt4 book ai didi

reactjs - 如何通过 react 上下文保持值(value)?

转载 作者:行者123 更新时间:2023-12-04 07:25:38 25 4
gpt4 key购买 nike

这里有 3 个基本组件 searchBar 指的是搜索栏表单searchPage 组件显示搜索结果,当然还有 app 组件,包含所有内容

机制:

  1. 用户在searchBar 组件 中提交输入,handleSubmit 函数被触发,这改变了状态setSearchedProducts 为输入值,通过useContext ANDhistory.push() 推送到 ("/SearchPage")。

import {useState, useContext } from "react";
import { useHistory } from "react-router-dom";
import { LocaleContext } from "../../../LocaleContext";



const SearchBar = () => {
const history = useHistory();
const {setSearchedTerm} = useContext(LocaleContext);


const handleSubmit = (SearchTerm) => {
setSearchedProducts(SearchTerm)
history.push("/SearchPage");
}


return (
<form>
<input onSubmit={(e) => handleSubmit(e.target.value)}>
</input>
<button type="submit">Submit</button>
</form>
)
}

export default SearchBar

  1. 值通过 React 上下文发送到 app 组件 并且状态被设置为值,同时仍然推送到(“/searchPage”)。

import { useState, useMemo } from "react";
import { searchBar, searchPage } from "./components";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import {LocaleContext} from "./LocaleContext"


const App = () => {

const [searchedTerm, setSearchedTerm] = useState("");


const providerValue = useMemo(() => ({searchedTerm, setSearchedTerm}),
[searchedTerm, setSearchedTerm])



return (
<Router>
<LocaleContext.Provider value={providerValue}>

<searchBar />

<Switch>
<Route exact path="/SearchPage">
<SearchPage />
</Route>
</Switch>

</LocaleContext.Provider>
</Router>

);
}

export default (App);

  1. 显示获取状态值的searchPage 组件通过使用 useContextuseEffectfetchProducts()函数被触发,它根据状态值。

import {useState, useEffect, useContext}  from 'react';
import { LocaleContext } from "../../LocaleContext";

const SearchPage = ({}) => {

const [products, setProducts] = useState([]);
const {searchedTerm} = useContext(LocaleContext);

const fetchProducts = (term) => {
setLoading(true);
const url = new URL(
"https://example/products"
);

let params = {
"query": term
};

Object.keys(params)
.forEach(key => url.searchParams.append(key, params[key]));

let headers = {
"Accept": "application/json",
"Content-Type": "application/json",
};

fetch(url, {
method: "GET",
headers: headers,
})
.then(response => response.json())
.then(json => {
setProducts(json);
});

}



useEffect(() => {
fetchProducts(searchedProducts)
}, [])


return (
{
products.map(product => (
<div>
{product.name}
</div>
))
}
)
}

export default SearchPage

问题:

  • 当路由器更改为 ("/searchPage") 组件状态值时丢失,这意味着它返回到 "" 值。 ?
  • 较小的问题,如果用户发送一个空字符串 (""),而 API 需要一个值,否则它会给出错误,有什么解决方案?
  • 有没有办法在重新加载页面后保留该值?

import {createContext} from "react";

export const LocaleContext = createContext(null);

如果需要,这是 localeContext 组件。

最佳答案

您必须在 onSubmit 处理程序中添加 e.preventDefault()。否则,您将重新加载页面,这会导致状态丢失。

关于reactjs - 如何通过 react 上下文保持值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68231399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com