首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法对'undefined‘或'null’的属性`user`进行结构分析

无法对'undefined‘或'null’的属性`user`进行结构分析
EN

Stack Overflow用户
提问于 2019-10-05 23:51:06
回答 2查看 15.9K关注 0票数 2

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

我使用的是nodejs、express、react、redux和jwt。

代码语言:javascript
运行
复制
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

这个问题总是在我写user:{user,loading}时发生,当我放入另一个我已经写过的代码时,它工作得很好,但每当我写的时候,页面就会失败。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-10-06 00:23:54

cannot destructure property user of 'undefined' or 'null'。这意味着当您第一次使用从服务器获取数据时,user data null or undefined。对服务器的API调用是异步的。第二次,你会得到user data

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

代码语言:javascript
运行
复制
const EditUser = ({
    user, 
    getCurrentUser, 
    history
}) => {
    if (user) {
        const { loading, ... } = user // Get another key in user object
    }
...
...
...
票数 2
EN

Stack Overflow用户

发布于 2020-06-04 00:55:01

代码语言:javascript
运行
复制
// When you try to destructure action object by default for the first time it would not have contain any keys defined by us, However it would contain default keys that redux provides. While Destructring this object would result in undefined or null because there is no matching key. So destructure inside the condition where it matches.
export const addBug = desc => ({
    type: actions.BUG_ADDED,
    payload: {
      description: desc
    }
  });
// i am dispatching the action in the below line
 store.dispatch(addBug('button is not clickable'));

// below i have destructred the action.payload object

let lastId = 0;
function reducer(state = [], action) {
    console.log(action);       
    switch(action.type) {
        case actions.BUG_ADDED:
            const {description} = action.payload;
            return [
              ...state,
              {
                id: ++lastId,
                description,
                resolved: false,
              },
            ];

            case actions.BUG_REMOVED:
                return state.filter(bug => action.payload.id !== bug.id);

            default: return state;
    }
}

export default reducer;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58249931

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档