因此,我尝试使用react context API创建一种存储,但遇到一个问题,当我使用useContext时,它返回未定义。 所以我的代码是这样的:
StateProvider.js
import React, { createContext, useContext, useReducer } from "react";
//Needed to track the basket and the user info
//DATA LAYER
export const StateContext = createContext();
// BUILD PROVIDER
export const StateProvider = ({ reducer, initialState, children}) => (
<StateContext.Provider value={useReducer(reducer, initialState)}>
{children}
</StateContext.Provider>
);
export const useStateValue = () => useContext(StateContext);
reducer.js
export const initialState = {
basket: ["asd", "asd"],
};
function reducer(state, action) {
switch(action.type){
case 'ADD_TO_BASKET':
//add item to basket
break;
case 'REMOVE_FROM_BASKET':
//remove item from basket
break;
default:
return state;
}
}
export default reducer;
index.js
import reducer, { initialState } from './state/reducer';
....
<StateProvider initalState={initialState} reducer={reducer}>
<App />
</StateProvider>
问题出在这个文件上,我尝试在控制台上记录从reducer.js initalState中获得的信息。
Header.js
import { useStateValue } from '../state/StateProvider'
...
function Header() {
console.log(useContext(StateContext))
const [{ basket }]= useStateValue();
console.log(basket);
错误是当我使用const [{ basket }]= useStateValue();
时,它说:无法读取未定义的属性'basket'。
答案 0 :(得分:0)
问题出在index.js上,initialState写得不好,由于ES6,我没有出现任何错误。