Cannot read property 'key' of undefined

来源:5-5 Action 和 Reducer 的编写

慕工程8196159

2020-07-23

实现点击按钮提交输入框的数据到列表,点击按钮提交的时候报错:Cannot read property ‘key’ of undefined。
store文件夹
index.js

import { createStore } from 'redux';
import reducer from './reducer';

const store = createStore(reducer);

export default store; 

reducer.js

const defaultState = {
    inputValue: '',
    list: []
}

export default (state = defaultState, action) => {
    if(action.type === 'input_value_change') {
        const newState = JSON.parse(JSON.stringify(state));
        newState.inputValue = newState.value;
        return newState;
    }
    if(action.type === 'change_list_value') {
        const newState = JSON.parse(JSON.stringify(state));
        newState.list.push(newState.inputValue);
        newState.inputValue = '';
        return newState;
    }
    return state;
}

TodoList.js

import React, { Component } from 'react';
import 'antd/dist/antd.css';
import { Input, List, Button } from 'antd';
import store from './store';

class TodoList extends Component{
    constructor(props) {
        super(props);
        this.state = store.getState();
        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleStoreChange = this.handleStoreChange.bind(this);
        this.handleBtnClick = this.handleBtnClick.bind(this);
        store.subscribe(this.handleStoreChange)
    }
    render() {
        return (
            <div 
                style={{marginTop: '20px', marginLeft: '20px'}}>
                <div>
                    <Input 
                        value={this.state.inputValue}
                        onChange={this.handleInputChange}
                        style={{width: '300px', marginRight: '10px'}}
                        placeholder="input message" />
                    <Button 
                        onClick={this.handleBtnClick}
                        type="primary">添加</Button>
                <List
                    style={{width: '300px', marginTop: '10px'}}
                    bordered
                    dataSource={this.state.list}
                    renderItem={item => (
                        <List.Item>
                            {item}
                        </List.Item>
                    )}
                />
                </div>
            </div>
        )
        
    }
    handleInputChange(e) {
        const action = {
            type: 'input_value_change',
            value: e.target.value
        }
        store.dispatch(action);
    }
    handleStoreChange() {
        this.setState(store.getState());
    }
    handleBtnClick() {
        const action = {
            type: 'change_list_value'
        }
        store.dispatch(action);
    }
}

export default TodoList;

图片描述

写回答

1回答

慕工程8196159

提问者

2020-07-24

问题已经解决

0
2
MountainK
我解决了
2020-12-23
共2条回复

React零基础入门到实战,完成企业级项目简书网站开发

主流新技术 React-redux,React-router4,贯穿基础语法

5275 学习 · 2496 问题

查看课程