如何删除数组redux商店中的项目?

时间:2017-08-06 12:17:07

标签: javascript reactjs redux

我是Redux和Redux的新手,所以我想尝试一个简单的待办事项清单。 我在商店里有阵列。它可以添加,但是当我删除项目时看到:

  

TypeError:无法读取未定义的属性“map”   在   var items = this.props.tasks.map((item,i)=>(this.props.deleteTask(item)} />));
  在 ListTODO.js

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducer from './reducer';

const store = createStore(reducer);

ReactDOM.render(
    <Provider store={store}>
        <App className="container" />
    </Provider>,
    document.getElementById('root'));
registerServiceWorker();

App.js

import React, { Component } from 'react';
import InputTask from './InputTask';
import ListTODO from './ListTODO';
import { connect } from 'react-redux';

class App extends Component {

    render() {
        return (<div>
            <strong>TODO LIST</strong>
            <InputTask addTask={this.props.addTask} /><br />
            <ListTODO tasks={this.props.store} deleteTask={this.props.deleteTask} />
        </div>);
    }
}

const mapStateToProps = state => {
    return {
        store: state
    }
}

const mapDispatchToProps = dispatch => {
    return {
        addTask: (task) => {
            dispatch({ type: 'UPDATE_LIST', payload: task })
        },
        deleteTask: (task) => {
            dispatch({ type: 'DELETE_TASK', payload: task })
        }
    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps)
    (App);

reducer.js

const initialState = ["task1", "task2"];

export default function todoList(state = initialState, action) {
    switch (action.type) {
        case 'UPDATE_LIST':
            return [
                ...state,
                action.payload
            ];
        case 'DELETE_TASK':
            console.log("DELETING", (action.payload))
            return
            state.filter(element => element !== action.payload);
        default: return state;
    }
}

ListTODO.js

import React, { Component } from 'react';
import TodoItem from './TodoItem';
import { connect } from 'react-redux';

 class ListTODO extends Component {

    constructor() {
        super();
    }

     render() {
          console.log("LIST TODO:"+ this.props.tasks);
          var items =this.props.tasks.map((item,i) => (<TodoItem item={item} key={i} deleteTask={(item)=>this.props.deleteTask(item)} />));
         return (
             <ul>
                 {items}                         
             </ul>
         );
     }
 }

export default ListTODO;

0 个答案:

没有答案