如何通过反应上下文保持价值?
Posted
技术标签:
【中文标题】如何通过反应上下文保持价值?【英文标题】:How to keep a value with react context? 【发布时间】:2021-09-14 18:35:43 【问题描述】:这里有 3 个基本组件 searchBar
指的是 搜索栏表单 和 searchPage
组件显示搜索结果,当然还有app
包含所有组件的组件。
机制:
-
用户在 searchBar 组件中提交输入,
handleSubmit
函数被触发,这改变了
setSearchedProducts
到输入值,由useContext
AND
被history.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
-
值通过反应上下文发送到 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);
-
显示searchPage组件,获取状态值
通过使用
useContext
和useEffect
,fetchProducts()
函数被触发,它根据
状态值。
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
组件。
【问题讨论】:
【参考方案1】:您必须在您的 onSubmit
处理程序中添加 e.preventDefault()
。否则,您将重新加载页面,这会导致状态丢失。
【讨论】:
有效,但有没有办法在重新加载页面后保留该值? 是的,您可以将数据本地存储在客户端(使用 localStorage / cookie 等)或服务器上。以上是关于如何通过反应上下文保持价值?的主要内容,如果未能解决你的问题,请参考以下文章