如何在其他反应组件中访问来自 useReducer(react) 的数据?
How do I access data from useReducer(react) in other react-components?
如何访问 Navbar
等其他组件中的 basket
以显示购物车的内容?
如果代码中有任何逻辑错误,请纠正我。
提前致谢。
const cartReducer = (state, action) => {
switch (action.type) {
// other cases
case 'INITIALIZE_CART':
return action.payload;
default:
return state;
}
};
const initialState = {
basket: []
};
const CartContext = createContext();
const CartProvider = ({ children }) => {
const [state, dispatch] = useReducer(cartReducer, initialState);
useEffect(() => {
axios.get('userdetails', {
headers: { "Authorization": localStorage.getItem('token') }
}).then(res => {
console.log(res)
dispatch({
type: 'INITIALIZE_CART',
payload: {
...initialState,
basket: res.data.cart
}
})
})
}, []);
return (
<CartContext.Provider value={{ state, dispatch }}>
{children}
</CartContext.Provider>
);
};
export const useStateValue = () => useContext(CartContext)
export default CartProvider
导入 CartState 并将其用于访问状态和传递操作
import { CartState } from '../Cart/StateProvider'
const [{ basket }, dispatch] = CartState()
如何访问 Navbar
等其他组件中的 basket
以显示购物车的内容?
如果代码中有任何逻辑错误,请纠正我。
提前致谢。
const cartReducer = (state, action) => {
switch (action.type) {
// other cases
case 'INITIALIZE_CART':
return action.payload;
default:
return state;
}
};
const initialState = {
basket: []
};
const CartContext = createContext();
const CartProvider = ({ children }) => {
const [state, dispatch] = useReducer(cartReducer, initialState);
useEffect(() => {
axios.get('userdetails', {
headers: { "Authorization": localStorage.getItem('token') }
}).then(res => {
console.log(res)
dispatch({
type: 'INITIALIZE_CART',
payload: {
...initialState,
basket: res.data.cart
}
})
})
}, []);
return (
<CartContext.Provider value={{ state, dispatch }}>
{children}
</CartContext.Provider>
);
};
export const useStateValue = () => useContext(CartContext)
export default CartProvider
导入 CartState 并将其用于访问状态和传递操作
import { CartState } from '../Cart/StateProvider'
const [{ basket }, dispatch] = CartState()