无法从我的商店中删除元素并升级我的组件

问题描述 投票:0回答:1

这是我的组件,我只列出一些元素

import React, {Component} from "react";

import {connect} from "react-redux";
import { delFruit} from "../../js/actions/index";

function mapDispatchToProps(dispatch)
{
    console.log(dispatch);
    return {
        delFruit: fruits => dispatch(delFruit(fruits))
    };
}

const mapStateToProps = state => {
    return {fruits: state.fruits};
};



class ConnectedList extends Component {
    constructor()
    {
        super();
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(el)
    {
        this.props.delFruit(el)
    }

    render()
    {
        // const fruits = this.state.fruits

        return (
            <div>
                <div className="title">Liste des courses</div>
                <ul className="list-group list-group-flush">
                    {
                        this.props.fruits.map((el, key) => (
                            <li key={key}>
                                {el.name} <i>( {el.price} € )</i> <i className="delete"  onClick={this.handleClick.bind(this, key)}></i>
                            </li>
                        ))
                    }
                </ul>
            </div>
        );

    }
}


const List = connect(mapStateToProps, mapDispatchToProps)(ConnectedList);

export default List;

当我想删除一个元素时,我使用这个脚本

import {ADD_FRUIT, DELETE_FRUIT, DOUBLE_FRUIT} from "../constants/action-types";
import fruits from "../../data/fruits";
const initialState = {
    fruits: fruits['elements'],
};

function rootReducer(state = initialState, action)
{
    if (action.type === ADD_FRUIT) {
        return Object.assign({}, {}, {
            fruits: state.fruits.concat(action.payload)
        });
    }
    if (action.type === DELETE_FRUIT) {
        delete state.fruits[action.payload];

        return Object.assign({}, {}, {
            fruits:state.fruits
        });

    }
    if (action.type === DOUBLE_FRUIT) {
    }
    return state;
}

export default rootReducer;

当我检查组件的状态时,元素被正确删除(在示例#2中)

enter image description here

但我的组件不会将其从列表中删除

我设法让它工作的唯一方法是这样做

return Object.assign({}, {}, {
            fruits:state.fruits.concat()
        });

代替

return Object.assign({}, {}, {
            fruits:state.fruits
        });
  • 为什么没有concat()我的组件没有更新
  • 如何做到这一点的好方法
  • 为什么我的数组在删除后保持空值
reactjs react-redux components
1个回答
1
投票

您可以使用spread运算符删除它。这是一个基本的片段,展示了如何做到这一点。

const state = {
  fruits: [1,2,3]
}

const action = {
  index: 1
}

const newState = [
              ...state.fruits.slice(0, action.index),
              ...state.fruits.slice(action.index + 1)
            ];

console.log(newState);

因此,您可以将代码修改为:

if (action.type === DELETE_FRUIT) {
    return {
        ...state,
        fruits: [
              ...state.fruits.slice(0, action.payload),
              ...state.fruits.slice(action.payload + 1)
        ]
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.