无法解构 'undefined' 的属性 `user`或 'null' [英] Cannot destructure property `user` of 'undefined' or 'null'

查看:68
本文介绍了无法解构 'undefined' 的属性 `user`或 'null'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 redux 检索用户信息时出错.我想从数据库中获取用户信息(姓名、密码和头像的地址),然后对其进行编辑.

我正在使用 nodejs、express、react、redux 和 jwt.

Actions/user.js从 'axios' 导入 axios;从 './alert' 导入 {setAlert};从./types"导入 {GET_USER, USER_ERROR};//获取当前用户资料export const getCurrentUser = () =>异步调度 =>{尝试 {const res = await axios.get('/api/users/me');派遣({类型:GET_USER,有效载荷:res.data});} 抓住(错误){派遣({类型:USER_ERROR,有效载荷:{味精:err.response.statusText,状态:err.response.status}});}};减速器/user.js从'../actions/types' 导入 {GET_USER, USER_ERROR, CLEAR_USER};常量初始状态 = {用户:空,用户:[],加载:真实,错误: {}}导出默认函数(状态 = 初始状态,动作){const {类型,有效载荷} = 动作;开关(类型){案例 GET_USER:返回{...状态,加载:假,用户:有效载荷};案例 USER_ERROR:返回{...状态,错误:有效载荷,加载:假};默认:返回状态;}}组件/edituser/EditUser.js从反应"导入反应、{useState、Fragment、useEffect};从 'prop-types' 导入 PropTypes;从'react-redux'导入{connect};从../../actions/user"导入 {getCurrentUser};从 'react-router-dom' 导入 {Link, withRouter};从'../layout/Alert'导入警报;从 '../util/InputSelector' 导入 InputSelector;const 编辑用户 = ({用户:{用户,加载},获取当前用户,历史}) =>{const [formData, setFormData] = useState({名称: '',电子邮件: '',密码: ''});useEffect(()=>{获取当前用户();});返回 (<片段><div className="col-md-12 mb-3"><div className="card"><div className="card-body"><div className="row"><div className="col-md-3 d-flex align-items-center">

<img className="img-fluid" src={'/uploads/noImg.jpg'}/>

<div className="col-md-9"><表格><div className="form-group"><label><i className="fas fa-user"></i>用户名</label><输入类型=文本"名称=技能"类名=表单控件"placeholder="Edita tu nombre de usuario"/>

<div className="form-group"><label><i className="fas fa-envelope"></i>电子邮件<输入类型=文本"名称=技能"类名=表单控件"placeholder="Edita tu email"/>

<div className="form-group"><label><i className="fas fa-key"></i>Contraseña</label><输入类型=文本"名称=技能"类名=表单控件"placeholder="Edita tu nombre de contraseña"/>

<div className="form-group" ><label><i class="fas fa-upload"></i>Imagen De Perfil</label><输入选择器/>

<div className="col-md-12 text-center"><button className="btn btn-primary btn-block"><i class="fas fa-check"></i>Guardar</button>

</表单>

</片段>);};EditUser.propTypes = {getCurrentUser: PropTypes.func.isRequired,用户:PropTypes.object.isRequired};const mapStateToProps = state =>({用户:state.user});导出默认连接(mapStateToProps,{getCurrentUser})(withRouter(EditUser));

https://imgur.com/xLzAu1A

问题总是在我写 user: {user, loading} 时发生,当我把另一个我已经完成的代码工作正常,但每当我写页面失败.

解决方案

cannot destruct property user of 'undefined' 或 'null'.这意味着当您第一次使用从服务器获取数据时 user data null or undefined.对服务器的 API 调用是异步的.第二次,您将获得用户数据.

我看到你使用 redux 作为道具的用户是来自服务器的 res.data.我不确定 res.data 的结构是什么?所以在组件中,你应该这样做:

const EditUser = ({用户,获取当前用户,历史}) =>{如果(用户){const { loading, ... } = user//获取用户对象中的另一个键}.........

Error retrieving user information with redux. I want to get the user information (name, password and address of the avatar from the db) and then edit it.

I'm using nodejs, express, react, redux and jwt.

Actions/user.js
import axios from 'axios';
import {setAlert} from './alert';

import {GET_USER, USER_ERROR} from './types';

//Get current users profile
export const getCurrentUser = () => async dispatch => {
    try {
        const res = await axios.get('/api/users/me');

        dispatch({
            type: GET_USER,
            payload: res.data
        });
    } catch (err) {
        dispatch({
            type:USER_ERROR,
            payload:{msg: err.response.statusText, status: err.response.status}
        });
    }
};

Reducers/user.js
import {GET_USER, USER_ERROR, CLEAR_USER} from '../actions/types';

const initialState = {
    user: null,
    users: [],
    loading: true,
    error: {}
}

export default function(state = initialState, action) {
    const {type, payload} = action;
    switch(type){
        case GET_USER:
        return{
            ...state,
            loading:false,
            user:payload
        };
        case USER_ERROR:
            return{
            ...state,
            error:payload,
            loading: false
        };
        default:
            return state;
    }
}

Components/edituser/EditUser.js
import React, {useState, Fragment, useEffect} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {getCurrentUser} from '../../actions/user';
import {Link, withRouter} from 'react-router-dom';
import Alert from '../layout/Alert';
import InputSelector from '../util/InputSelector';

const EditUser = ({
    user:{user,loading}, 
    getCurrentUser, 
    history}) => {
    const [formData, setFormData] = useState({
        name: '',
        email: '',
        password: ''
    });

    useEffect(()=>{
        getCurrentUser();
    });
    return (
        <Fragment>
      <div className="col-md-12 mb-3">
                <div className="card">
                    <div className="card-body">
                        <div className="row">
                            <div className="col-md-3 d-flex align-items-center">
                            <div className="img">
                            <img className="img-fluid" src={'/uploads/noImg.jpg'} />
                        </div>
                            </div>
                        <div className="col-md-9">
                        <form>
                            <div className="form-group">
                                <label><i className="fas fa-user"></i> Username</label>
                                <input 
                                type="text" 
                                name="skills"
                                className="form-control" 
                                placeholder="Edita tu nombre de usuario"
                                />
                            </div>
                            <div className="form-group">
                                <label><i className="fas fa-envelope"></i> Email</label>
                                <input 
                                type="text" 
                                name="skills"
                                className="form-control" 
                                placeholder="Edita tu email"
                                />
                            </div>
                            <div className="form-group">
                                <label><i className="fas fa-key"></i> Contraseña</label>
                                <input 
                                type="text" 
                                name="skills"
                                className="form-control" 
                                placeholder="Edita tu nombre de contraseña"
                                />
                            </div>
                            <div className="form-group" >
                            <label><i class="fas fa-upload"></i> Imagen De Perfil</label>
                        <InputSelector/>
                        </div>
                        <div className="col-md-12 text-center">
                        <button className="btn btn-primary btn-block"><i class="fas fa-check"></i> Guardar</button>
                        </div>
                        </form> 
                        </div>
                        </div>
                    </div>
                </div>
            </div>
            </Fragment>
    );
};
EditUser.propTypes = {
    getCurrentUser: PropTypes.func.isRequired,
    user: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
        user: state.user
     });

export default connect(mapStateToProps, {getCurrentUser}) 
(withRouter(EditUser));

https://imgur.com/xLzAu1A

The problem always happens when I write user: {user, loading}, when I put another code that I already have done it works fine, but whenever I write that the page fails.

解决方案

cannot destructure property user of 'undefined' or 'null'. This mean user data null or undefined at the first time when you use fetch data from server. The API call to server is async. At the second time, you will got user data.

I see the user that you take as props with redux is res.data from server. I'm uncertain structure of res.data what is? So in component, you should be do like:

const EditUser = ({
    user, 
    getCurrentUser, 
    history
}) => {
    if (user) {
        const { loading, ... } = user // Get another key in user object
    }
...
...
...

这篇关于无法解构 &amp;#39;undefined&amp;#39; 的属性 `user`或 &amp;#39;null&amp;#39;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆