Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/456.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法对';未定义';或';空';_Javascript_Reactjs_Mongodb_Redux - Fatal编程技术网

Javascript 无法对';未定义';或';空';

Javascript 无法对';未定义';或';空';,javascript,reactjs,mongodb,redux,Javascript,Reactjs,Mongodb,Redux,使用redux检索用户信息时出错。 我想获得用户信息(姓名,密码和地址的化身从数据库),然后编辑它 我使用nodejs、express、react、redux和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

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

我使用nodejs、express、react、redux和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));
Actions/user.js
从“axios”导入axios;
从“/alert”导入{setAlert};
从“./types”导入{GET_USER,USER_ERROR};
//获取当前用户配置文件
导出常量getCurrentUser=()=>异步调度=>{
试一试{
const res=wait axios.get('/api/users/me');
派遣({
类型:GET_用户,
有效载荷:res.data
});
}捕捉(错误){
派遣({
类型:用户错误,
有效负载:{msg:err.response.statusText,状态:err.response.status}
});
}
};
Reducers/user.js
从“../actions/types”导入{GET_USER,USER_ERROR,CLEAR_USER};
常量初始状态={
用户:null,
用户:[],
加载:对,
错误:{}
}
导出默认函数(状态=初始状态,操作){
const{type,payload}=action;
开关(类型){
案例获取用户:
返回{
……国家,
加载:false,
用户:有效载荷
};
案例用户错误:
返回{
……国家,
错误:有效载荷,
加载:错误
};
违约:
返回状态;
}
}
组件/edituser/edituser.js
从“React”导入React,{useState,Fragment,useffect};
从“道具类型”导入道具类型;
从'react redux'导入{connect};
从“../../actions/user”导入{getCurrentUser};
从“react router dom”导入{Link,withRouter};
从“../layout/Alert”导入警报;
从“../util/InputSelector”导入InputSelector;
常量EditUser=({
用户:{用户,正在加载},
getCurrentUser,
历史})=>{
常量[formData,setFormData]=useState({
名称:“”,
电子邮件:“”,
密码:“”
});
useffect(()=>{
getCurrentUser();
});
返回(
用户名
电子邮件
康瑟斯尼娜
性能图像
瓜达尔
);
};
EditUser.propTypes={
getCurrentUser:PropTypes.func.isRequired,
用户:PropTypes.object.isRequired
};
常量mapStateToProps=状态=>({
用户:state.user
});
导出默认连接(mapStateToProps,{getCurrentUser})
(带路由器(编辑用户));


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

无法对“undefined”或“null”的属性user进行解构。
。这意味着当您第一次使用从服务器获取数据时,
用户数据
为空或未定义
。对服务器的API调用是异步的。第二次,您将获得
用户数据

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

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

分派({type:GET_USER,payload:res.data});你能显示
res.data对象吗
?router.get('/me',auth,async(req,res)=>{try{const user=wait user.findOne({u id:req.user.id});if(!user){return res.status(400).json({msg:'没有用户'})}res json(user);}catch(err){console.err(err.message);res.status(500.send('Server Error');});虽然这段代码可以解决这个问题,但如何以及为什么解决这个问题将真正有助于提高您的帖子质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请在回答中添加解释,并说明适用的限制和假设。我添加了解释,希望现在能有所帮助。
// 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;