将对象添加到react-redux中的嵌套数组

时间:2019-05-22 18:28:36

标签: reactjs redux react-redux

我在网上找到了很多解决方案,但是我已经尽了一周的努力,没有找到解决方法。我相信是减速器ADD_GOAL 的错误,这就是为什么我将其留空。

非常感谢! :)

我想将对象添加到目标数组。我一直想将目标初始化为空,但我希望能够自由添加和删除对象。想法是保存这样的对象。

{
  list: {
    '0': {
      id: 0,
      dueDate: 'By May 28th I Will have: ',
      goals: [
        {0: {...}
         1: {...}
         3: {...}
}
      ]
    }
   '1':{
      id: 0,
      dueDate: 'By June 31st I Will have: ',
      goals: [
        {2: {...}
         4: {...}
  }
}

减速器

export default (state = {}, action) => {
  let copyList = [{ description: '213', aim: 12, progress: 2, percentage: 20 }];
  switch (action.type) {
    case 'ADD_DUEDATE':
      return { ...state, [action.payload.id]: action.payload }
    case 'ADD_GOAL':
      return {

      }
    case 'DELETE_TODO':
      return state.filter((item, index) => index !== action.payload)
    default:
      return state;
  }
}

组件

import React from 'react';
import { connect } from 'react-redux';

class List extends React.Component {
  state = {
    id: 0,
    goalId: 0
  }

  createDueDate = () => {
    this.props.add({
      id: this.state.id,
      dueDate: "By May 28th I Will do something: ",
      goals: [{}]
    })
    this.setState({ id: this.state.id + 1 });
  }

  addGoal = () => {
    this.props.addToList({
      goals:
        [{ id: this.state.goalId, description: '213', aim: 12, progress: 2, percentage: 20 }]
    })
    this.setState({ goalId: this.state.goalId + 1 })

  }

  render() {
    return (
      <div>
        <div>
          <button className="btn btn-secondary" onClick={this.createDueDate}></button>
        </div>

        <div>
          <button className="btn btn-primary" onClick={this.addGoal}></button>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    list: state.list
  }
}

function mapDispatchToProps(dispatch) {
  return {
    add: (value) => {
      dispatch({ type: 'ADD_DUEDATE', payload: value })
    },
    get: (id) => {
      dispatch({ type: 'GET_DUEDATE', payload: id })
    },
    addToList: (value) => {
      dispatch({ type: 'ADD_GOAL', payload: value })
    }
  }
}

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

1 个答案:

答案 0 :(得分:1)

让我们假设化简器中嵌套有一组项目:

const initialState = {
    items : {
        deepItem  :[1, 2, 2],
        reallyDeepItem: {
            a : [1,2,3]
            b : {'a', 'c'}
        }
    }
}

现在,我们假设有2个操作,一个在state.items.deepItem上添加一个我们将称为ADD_DEEP_ITEM的项目,另一个在state.items.reallyDeepItem.a上插入一个名为{{1}的项目}。让我们编写我们的减速器:

ADD_DEEPER_ITEM

就是这样,已正确更新!只需记住始终散布所有属性,然后覆盖所需属性即可。