javascript - redux 道具未定义

平欧

我正在尝试编写一个聊天网络应用程序。在下面的代码中,如果我排除了与对话有关的所有代码,它就可以正常工作(如果我只加载用户名并尝试发送消息就可以了)。但是,一旦我添加了与对话有关的所有代码,它就会不断弹出错误消息“this.props.recipients 未定义”。但在我添加任何与对话相关的代码(即 loadConversations() 和对话列表 ())之前,它运行良好。在添加这些代码之前,我能够访问 this.prop.recipients(如 userList 中所示)。我究竟做错了什么??

import React from 'react';
import { connect, Provider } from 'react-redux';
import fetch from 'isomorphic-fetch';
import * as actions from './actions/index'


class Chat extends React.Component{ 
    constructor(props){
        super(props);
        this.state = {recipientId: '', messageBuffer:'asdfadsfasdf'};
        this.userList = this.userList.bind(this);
        this.changeRecipient = this.changeRecipient.bind(this);
        this.insertText = this.insertText.bind(this);
    }
    componentWillMount(){
        this.props.loadConversations();

        this.props.loadRecipients();
    }

    userList(){
        if(this.props.recipients.length == 0){
            console.log('why??');   
        }
        else{
            console.log('here');
            console.log(this.props.recipients.length)
            return this.props.recipients.map(user=>(<option key = {user._id} value = {user._id}>{user.name}</option>));
        }
    }


    changeRecipient(e){
        e.preventDefault();
        this.setState({recipientId: e.target.value});
    }

    insertText(e){
        e.preventDefault();
        this.setState({messageBuffer:e.target.value});
    }

    newMessage(e){
        e.preventDefault();
        var recipientId = this.state.recipientId;
        if (recipientId ===''){
            recipientId = this.props.recipients[0]._id;
        }
        console.log(recipientId);
        console.log(this.state.messageBuffer);
        fetch('/newMessage',
        {
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
              'Authorization' : localStorage.getItem("token"),

            },
            method: "POST",
            body: JSON.stringify({recipient:recipientId, composedMessage:this.state.messageBuffer})
        })
        .then(function(response) {
            console.log(response);
        })
    }

    conversationList(){
        console.log('in conversation list');
        console.log(this.props.conversations.length);
    }

    render(){

        return (
            <div>
                <form onSubmit = {(e) => this.newMessage(e)}>
                    <select name="recipient" onChange = {(e)=> this.changeRecipient(e)}>
                        {this.userList()}
                    </select>
                    <input type = 'text' name = 'composedMessage' onChange = {(e)=> this.insertText(e)}></input>
                    <input type="submit" value="Submit" ></input>
                </form> 
                {this.conversationList}
            </div>)
    }


}

function mapStateToProps(state) {  
    return {recipients: state.recipients, conversations: state.conversations};
}

export default connect(mapStateToProps, actions)(Chat);

这是我的动作创作者

import {LOAD_RECIPIENTS, LOAD_CONVERSATIONS } from './type'

export function loadRecipients(){
    return function(dispatch){
        fetch("/getRecipients",
        {
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
              'Authorization' : localStorage.getItem("token")
            },
            method: "GET",
        })
        .then(function(response) {
            return response.json();
        })
        .then(json=>{
            console.log(json.users);
            console.log('load recipients here!!');
            dispatch({type: LOAD_RECIPIENTS, recipients: json.users});
        })
        .catch(err=>{
            console.log(err);
        });
    }
}

export function loadConversations(){
    return function(dispatch){
        fetch("/getConversations",
        {
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
              'Authorization' : localStorage.getItem("token")
            },
            method: "GET",
        })
        .then(function(response) {
            return response.json();
        })
        .then(json=>{
            console.log(json.conversations);
            console.log('load conversations here!!');
            dispatch({type: LOAD_CONVERSATIONS , conversations: json.conversations});
        })
        .catch(err=>{
            console.log(err);
        });
    }
}

这是减速机

import {LOAD_RECIPIENTS,LOAD_CONVERSATIONS} from '../actions/type.js';

const initial = {recipients:[], conversations:[]}


export default function(state = initial, action){
    switch (action.type){
        case LOAD_RECIPIENTS:
            return {recipients : action.recipients};
            break;
        case LOAD_CONVERSATIONS:
            return {conversations : action.conversations};
            break;
        default:
            return state;
    }
}

这是错误信息

堆栈:“userList@ http://localhost:8000/chatbundle.js:24584:1 \nrender@ http://localhost:8000/chatbundle.js:24657:7 \n_renderValidatedComponentWithoutOwnerOrContext/renderedElement<@ http://localhost: 8000/chatbundle.js:19501:16 \nmeasureLifeCyclePerf@ http://localhost:8000/chatbundle.js:18781:12 \n_renderValidatedComponentWithoutOwnerOrContext@ http://localhost:8000/chatbundle.js:19500:25 \renderValidComponentn@ http: //localhost:8000/chatbundle.js:18781:12 //localhost:8000/chatbundle.js:19527:27 \n_updateRenderedComponent@ http://localhost:8000/chatbundle.js:19451:31 \n_performComponentUpdate@ http://localhost:8000/chatbundle.js:19429:5 \更新组件@http://localhost:8000/chatbundle.js:19350:7 \nreceiveComponent@ http://localhost:8000/chatbundle.js:19252:5 \nreceiveComponent@ http://localhost:8000/chatbundle.js:2755: 5 \n_updateRenderedComponent@ http://localhost:8000/chatbundle.js:19459:7 \n_performComponentUpdate@ http://localhost:8000/chatbundle.js:19429:5 \nupdateComponent@ http://localhost:8000/chatbundle。 js:19350:7 \nperformUpdateIfNecessary@ http://localhost:8000/chatbundle.js:19266:7 \nperformUpdateIfNecessary@ http://localhost:8000/chatbundle.js:2787:5 \nrunBatchedUpdates@ http://localhost: 8000/chatbundle.js:1399:5 \nperform@http://localhost:8000/chatbundle.js:3913:13 \nperform@ http://localhost:8000/chatbundle.js:3913:13 \nperform@ http://localhost:8000/chatbundle.js:1338: 12 \nflushBatchedUpdates@ http://localhost:8000/chatbundle.js:1421:7 \ncloseAll@ http://localhost:8000/chatbundle.js:3979:11 \nperform@ http://localhost:8000/chatbundle。 js:3926:11 \nbatchedUpdates@ http://localhost:8000/chatbundle.js:20569:14 \nenqueueUpdate@ http://localhost:8000/chatbundle.js:1449:5 \nenqueueUpdate@ http://localhost: 8000/chatbundle.js:5857:3 \nenqueueSetState@ http://localhost:8000/chatbundle.js:6051:5 \nReactComponent.prototype.setState@http://localhost:8000/chatbundle.js:6663:3 \nonStateChange@ http://localhost:8000/chatbundle.js:10542:11 \ndispatch@ http://localhost:8000/chatbundle.js:10848: 7 \ncreateThunkMiddleware/http://localhost:8000/chatbundle.js:24511:16\ndispatch@ http://localhost:8000/chatbundle.js:24261:18 \nloadConversations/http://localhost:8000/chatbundle。 js:25207:4\n"

平欧

结果发现我的减速器有问题。我忘记添加扩展运算符,因此它完全删除了以前的状态。

它应该是

export default function(state = initial, action){
    switch (action.type){
        case LOAD_RECIPIENTS:
            return {...state,recipients : action.recipients};
            break;
        case LOAD_CONVERSATIONS:
            return {...state, conversations : action.conversations};
            break;
        default:
            return state;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Javascript / Redux中未定义的对象属性

来自分类Dev

Javascript / Redux中未定义的对象属性

来自分类Dev

Redux 状态未定义

来自分类Dev

未处理的拒绝(TypeError):无法读取 redux 中未定义的属性“道具”

来自分类Dev

未捕获的类型错误:无法读取 react-redux 中未定义的属性“道具”

来自分类Dev

如何解决 React 和 Redux 抛出无法读取未定义错误的属性“道具”?

来自分类Dev

React Redux - 在动作道具上未定义无限滚动调用

来自分类Dev

JavaScript“未定义”

来自分类Dev

在组件状态和道具与Redux中使用相同的变量名,我得到未定义道具的错误

来自分类Dev

Redux测试-ReferenceError:未定义localStorage

来自分类Dev

在mapStateToProps中未定义Redux状态

来自分类Dev

未定义不是函数-响应redux

来自分类Dev

Redux:TypeError:e 未定义

来自分类Dev

Angular - Redux Thunk AppState 未定义

来自分类Dev

使用 redux 的未定义值

来自分类Dev

尽管使用道具而不是状态,但无法读取React-redux上未定义错误的属性“ map”

来自分类Dev

JavaScript范围未定义

来自分类Dev

未定义Javascript文档

来自分类Dev

未定义值javascript

来自分类Dev

未定义FB javascript

来自分类Dev

变量未定义-JavaScript

来自分类Dev

文字未定义-JavaScript

来自分类Dev

Javascript数组未定义?

来自分类Dev

javascript对象未定义

来自分类Dev

Javascript“ ---未定义”错误

来自分类Dev

javascript方法未定义

来自分类Dev

Javascript Cookie未定义

来自分类Dev

未定义Javascript函数

来自分类Dev

Javascript:参数未定义?