如何在设置路由的情况下添加 ```Context```?
How to add ```Context``` with routes set up?
我想在我的 App.js 中添加 searchContext
上下文,以便我的 Navbar
和 Results
组件可以访问其中的变量。我将如何设置我的路线?我试着用它们添加 with 但那没有用。这是代码。
<Router>
// Where does <searchContext.Provider> go?
<Navbar></Navbar>
<Routes>
<Route exact path='/' element={<Home />} />
<Route path='/results'>
<Route path='/results/:value' element={<Results />} />
{/*<Route path='/results/:value/:slot' element={<Slot />}*/}
</Route>
// Another route that has nothing to do with searchContext
</Routes>
</Router>
编辑:添加了“// 与 searchContext 无关的另一条路线”
如果我是你,我会把所有东西都用供应商包装起来,只要它不重。
你好,这符合对上下文的一般理解Api,
现在你的文件夹结构是你的选择,但我会在这里非常简短
//on your context file searchContext.js
import {useState,createContext} from 'react';
export const SearchContext = createContext(null);
export const ContextProvider = props => {
const [search,setSearch] = useState(null);
return <SearchContext.Provider value = {{search,setSearch}}>
{children>
</SearchContext.Provider>
}
//now on your route.js
import { ContextProvider} from '../your/path/file';
....
<Router>
// Where does <searchContext.Provider> go?
<ContextProvider>
<Navbar></Navbar>
<Routes>
<Route exact path='/' element={<Home />} />
<Route path='/results'>
<Route path='/results/:value' element={<Results />} />
{/*<Route path='/results/:value/:slot' element={<Slot />}*/}
</Route>
// Another route that has nothing to do with searchContext
</Routes>
</ContextProvider>
</Router>
我想在我的 App.js 中添加 searchContext
上下文,以便我的 Navbar
和 Results
组件可以访问其中的变量。我将如何设置我的路线?我试着用它们添加 with 但那没有用。这是代码。
<Router>
// Where does <searchContext.Provider> go?
<Navbar></Navbar>
<Routes>
<Route exact path='/' element={<Home />} />
<Route path='/results'>
<Route path='/results/:value' element={<Results />} />
{/*<Route path='/results/:value/:slot' element={<Slot />}*/}
</Route>
// Another route that has nothing to do with searchContext
</Routes>
</Router>
编辑:添加了“// 与 searchContext 无关的另一条路线”
如果我是你,我会把所有东西都用供应商包装起来,只要它不重。
你好,这符合对上下文的一般理解Api, 现在你的文件夹结构是你的选择,但我会在这里非常简短
//on your context file searchContext.js
import {useState,createContext} from 'react';
export const SearchContext = createContext(null);
export const ContextProvider = props => {
const [search,setSearch] = useState(null);
return <SearchContext.Provider value = {{search,setSearch}}>
{children>
</SearchContext.Provider>
}
//now on your route.js
import { ContextProvider} from '../your/path/file';
....
<Router>
// Where does <searchContext.Provider> go?
<ContextProvider>
<Navbar></Navbar>
<Routes>
<Route exact path='/' element={<Home />} />
<Route path='/results'>
<Route path='/results/:value' element={<Results />} />
{/*<Route path='/results/:value/:slot' element={<Slot />}*/}
</Route>
// Another route that has nothing to do with searchContext
</Routes>
</ContextProvider>
</Router>