如何修复“无法读取未定义的属性”?

时间:2020-10-01 20:00:38

标签: javascript reactjs firebase

如何解决此错误?我已经尝试过,但仍然无法做到。

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);

1 个答案:

答案 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();