【发布时间】:2021-07-31 04:37:06
【问题描述】:
我是第一次学习反应和使用上下文。我正在尝试通过上下文将 state 和 setState 函数传递给所有子组件,但我不断收到错误消息。
这就是我创建上下文的方式:
import {createContext} from 'react'
const Context = createContext({
wishlist: [],
setObject: () => {}
});
export default Context
这是我创建 useState 钩子并将上下文传递给子组件的地方:
const [wishList, setwishList] = useState ([])
return (
<div className={darkMode === false ? 'lightMode' : 'darkMode'}>
<Router>
<Context.Provider value={{wishList, setwishList}} >
<Header setDarkMode={setDarkMode} darkMode={darkMode} wishListcounter={wishListcounter} productsDataBase={productsDataBase} setProductsArray={setProductsArray} />
<Switch>
<Route path='/' exact>
<Hero darkMode={darkMode} productsDataBase={productsDataBase} setProductsArray={setProductsArray} />
</Route>
<Route path='/gallery'>
<Gallery darkMode={darkMode} productsDataBase={productsDataBase} productsArray={productsArray} setProductsArray={setProductsArray} wishListcounter={wishListcounter} setwishListcounter={setwishListcounter}/>
</Route>
<Route path='/item'>
<Item />
</Route>
<Route path='/wishlist'>
<Wishlist wishListcounter={wishListcounter} />
</Route>
<Route path='/about'>
<About productsDataBase={productsDataBase} setProductsArray={setProductsArray} />
</Route>
</Switch>
<Footer />
</Context.Provider>
</Router>
</div>
); }
这就是我使用上下文、读取状态并修改它的地方。
// Hook used to access wishlist and modify it
const {wishList, setwishList} = useContext(Context)
function handleWishClick (id) {
wishList.includes(id) ? wishList.splice(wishList.indexOf(id), 1) : setwishList(wishList.push(id))
console.log(wishList)
}
我得到的错误是 TypeError: wishList.includes is not a function。 这只会在状态被修改一次后发生。
我的意思是,handleWishClick 函数运行一次很好,但是当我再次尝试运行它时,状态不会被识别。
关于如何解决这个问题的任何提示?
完整代码可以在这里找到:https://github.com/coccagerman/sweetKicks
提前致谢!
【问题讨论】:
-
我认为这里没有必要使用 setState。您可以向 Context Provider 提供一个简单的 JSON 对象,其中包含所有必要的属性。此外,github 链接给出 404 错误。尝试制作一个工作示例here
标签: reactjs react-hooks use-state use-context