简体   繁体   English

如何通过反应上下文保持价值?

[英]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:机制:

  1. the user submits an input in the searchBar component , the 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() .用户在searchBar 组件中提交输入, 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

  1. the value gets sent to the app component by react context and the state gets set to the value while still pushing to the ("/searchPage").该值通过反应上下文发送到应用程序组件,并且 state 被设置为该值,同时仍推送到(“/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. displaying the searchPage component , which gets the state value by using useContext , and with useEffect , the fetchProducts() function gets fired, that fetches a set of products based on the state value.显示searchPage 组件,该组件使用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:问题:

  • when the router changes to the ("/searchPage") component state value get lost, meaning it returns to "" value.当路由器更改为 ("/searchPage") 组件 state 值丢失时,意味着它返回到""值。 ? ?
  • lesser problem, if the user sends an empty string (" "), and the API needs a value or it will give an error, what is the solution to that?较小的问题,如果用户发送一个空字符串(“”),而API需要一个值,否则会报错,解决办法是什么?
  • is there a way of keeping the value after reloading the page?有没有办法在重新加载页面后保持价值?

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM