M. *_*mov 2 reactjs react-context react-hooks
不久,当我尝试在我的组件之一中将 useState 与 useContext 一起使用时,所有页面都消失了。UseState 出于某种原因阻止了我的路由器,我不知道为什么......你能告诉我我的错误在哪里吗?
下面的一些代码:Index.js
export default function App() {
const [value, setValue] = useState(false) -----> here I set the state
return (
<BrowserRouter>
<UserContext.Provider value={{ value, setValue }}>
<Routes>
<Route path='/' element={<Layout />}>
<Route index element={<Home />} />
<Route path='Home' element={<Home />} />
<Route path='Menu' element={<Menu />} />
<Route path='Story' element={<Story />} />
<Route path='Coffee' element={<Coffee />} />
<Route path='Cart' element={<Cart />} />
</Route>
</Routes>
</UserContext.Provider>
</BrowserRouter>
)
}
// ReactDOM.render(<App />, document.getElementById("root"))
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<App />)
Run Code Online (Sandbox Code Playgroud)
Buy.js 组件
import { useState } from "react"
import { useContext } from "react"
import { UserContext } from "../../UserContext"
const Buy = () => {
const [buttonText, setButtonText] = useState("Add to cart")
const [isActive, setIsActive] = useState(false)
// const [value, setValue] = useContext(UserContext) --> after I declare state everything disappears
const addToCart = () => {
setIsActive((current) => !current)
// setValue(true)
if (isActive) {
setButtonText("Add to cart")
}
}
return (
<div>
<button
class='buy'
style={{
fontSize: isActive ? "0.8rem" : "1rem",
color: isActive ? "lightgray" : "white",
}}
onClick={() => {
addToCart()
}}
>
{buttonText}
</button>
</div>
)
}
export default Buy
Run Code Online (Sandbox Code Playgroud)
UserContext.js
import { createContext } from "react"
export const UserContext = createContext(null)
Run Code Online (Sandbox Code Playgroud)
实际上,我只需要这个上下文用于路线“咖啡”和“购物车”,但如果我只包装这两条路线将是同样的问题,并且一切都会消失。我应该在 Layout.jsx 中使用 Context 而不是 Index.js 吗?谢谢。
const Layout = () => {
return (
<>
<Navbar />
<Outlet />
<Footer/>
</>
);
};
export default Layout;
Run Code Online (Sandbox Code Playgroud)
你的上下文提供了一个对象,而不是一个array ,因此您在使用它时应该使用花括号来解构:
const { value, setValue } = useContext(UserContext);
Run Code Online (Sandbox Code Playgroud)
或者,如果您想保留这种解构方式,您可以提供一个数组:
<UserContext.Provider value={[value, setValue]}>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5550 次 |
| 最近记录: |