[英]How to keep a value with react context?
Here are 3 basic components searchBar
which refers to the search bar form and, the searchPage
component which displays the search results , and of course, the app
component which contains them all .这里有 3 个基本组件
searchBar
指的是搜索栏表单, searchPage
组件显示搜索结果,当然还有包含它们的app
组件。
mechanism:机制:
handleSubmit
function gets fired, which changes the state of setSearchedProducts
to the input value, by useContext
AND getting pushed to the ("/SearchPage") by history.push()
.handleSubmit
function 被触发,这将 setSearchedProducts 的setSearchedProducts
更改为输入值,通过useContext
并通过history.push()
。 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
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);
useContext
, and with useEffect
, the fetchProducts()
function gets fired, that fetches a set of products based on the state value.useContext
获取 state 值,并使用useEffect
触发fetchProducts()
function,该组件基于 Z9ED39E2EA9312EF586B73E 值获取一组产品。 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
Issues:问题:
import {createContext} from "react"; export const LocaleContext = createContext(null);
this is the localeContext
component if needed.如果需要,这是
localeContext
组件。
you have to add e.preventDefault()
in your onSubmit
handler.您必须在
onSubmit
处理程序中添加e.preventDefault()
。 Otherwise you're getting a page reload which causes a state loss.否则,您将重新加载页面,从而导致状态丢失。
I noticed "setSearchedProducts" & "setSearchedTerm" should be the same in your code below.我注意到下面的代码中的“setSearchedProducts”和“setSearchedTerm”应该是相同的。 This might be your issue!
这可能是你的问题!
const SearchBar = () => {... const {setSearchedTerm} = useContext(LocaleContext); const handleSubmit = (SearchTerm) => { setSearchedProducts(SearchTerm)... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.