带有react TypeError的错误useContext:无法读取null的属性“电子邮件”

时间:2020-05-04 19:53:45

标签: reactjs react-hooks use-effect use-reducer use-context

我试图在React中使用上下文和reducer来获取一个钩子的值,但是当我记录json时,我收到的json的三倍,第一个值为null,第二个和第三个包含正确的json。 当我尝试在返回文字{user.email}中使用它时,出现错误“ TypeError:无法读取null的属性'email'”。但是,为什么我登录并看到json对象却无法返回?

感谢您的帮助,对不起,您的代码过多。

function Profile() {

    useEffect(() => {
        userAuthenticated();
    }, []);

    // Extraer la información de autenticación
    const authContext = useContext(AuthContext);
    const { user, userAuthenticated } = authContext;

    return (
        <div>{user.email}</div>
    );
}

export default Profile;
const token = localStorage.getItem('token');
if (token) {
  tokenAuth(token);
}

function App() {
  return (

    <AlertState>
      <AuthState>
        <ModalState>
          <Router>
            <Navigation />
            <Route path='/' exact component={Header} />
            <Route path='/' exact component={CarouselCards} />
            <Route path='/newtournament' component={TorneoForm} />
            <Route path='/rankingtables' exact component={RankingsTables} />
            <Route path='/tournamenttable' exact component={TournamentTable} />
            <Route path='/playerlist' exact component={PlayerList} />
            <Route path='/' exact component={Draws} />
            <Route path='/' exact component={TopEvList} />
            <Route path="/player" component={Profile} />
            <Footer />
          </Router>
        </ModalState>
      </AuthState>
    </AlertState>
  );
}

export default App;
import {
    SUCCESS_SIGNUP,
    SIGNUP_ERROR,
    GET_USER,
    SUCCESS_LOGIN,
    LOGIN_ERROR,
    LOG_OUT
} from '../../types';

const AuthState = props => {
    const initialState = {
        token: localStorage.getItem('token'),
        authenticated: null,
        user: null,
        message: null,
        loading: true
    }

    const [state, dispatch] = useReducer(AuthReducer, initialState);

    // Retorna el usuario autenticado
    const userAuthenticated = async () => {
        const token = localStorage.getItem('token');
        if (token) {
            tokenAuth(token);
        }

        try {
            const response = await axiosClient.get('/api/auth');
            dispatch({
                type: GET_USER,
                payload: response.data.user
            });

        } catch (error) {
            console.log(error.response);
            dispatch({
                type: LOGIN_ERROR
            })
        }
    }

    return (
        <AuthContext.Provider
            value={{
                token: state.token,
                authenticated: state.authenticated,
                user: state.user,
                message: state.message,
                loading: state.loading,
                signupUser,
                logIn,
                userAuthenticated,
                logOut
            }}
        >{props.children}

        </AuthContext.Provider>
    )
}
export default AuthState;
import {
    SUCCESS_SIGNUP,
    SIGNUP_ERROR,
    GET_USER,
    SUCCESS_LOGIN,
    LOGIN_ERROR,
    LOG_OUT
} from '../../types';

export default (state, action) => {
    switch (action.type) {
        case GET_USER:
            return {
                ...state,
                authenticated: true,
                user: action.payload,
                loading: false
            }

        default:
            return state;
    }
}

0 个答案:

没有答案