如何解决此错误?我已经尝试过,但仍然无法做到。
TypeError: Cannot read property 'user' of undefined
App
C:/Users/Bogosyna/Desktop/IT job projects/roro-facebook/src/App.js:11
8 | import {useStateValue} from "./StateProvider";
9 |
10 | function App() {
> 11 | const [{ user }, dispatch] = useStateValue();
12 |
13 | return (
14 | <div className="app">
这是useStateValue()的实现
import React, { createContext, useContext, useReducer } from "react";
export const StateContext = createContext();
export const StateProvider = ({ reducer, initialState, children}) => (
<StateContext.Provider value={useReducer(reducer, initialState)}>
{children}
</StateContext.Provider>
);
export const useStateValue = () => useContext(StateContext);
答案 0 :(得分:0)
您是否尝试向initialState
提供user
对象?
initialState = {
user: {},
}
然后将其传递给useReducer(reducer, initialState)
。
如果这不是您可以做的,请不要这么早破坏用户,请执行以下操作:
const [values, dispatch] = useStateValue();
console.log(values.user) // See when the user is available
或为用户提供初始的空对象,如下所示:
const [{user} = {}, dispatch] = useStateValue();