React,Redux 单击删除项目会删除所有项目

React, Redux Deleting an item on click deletes all items

我需要重新审视这个问题。当我慢慢学习 React 和 Redux 时,我 运行 又遇到了障碍。

/actions/items.js

export const DELETE_ITEM = "DELETE_ITEM"
export function deleteItem(id) {
  return {
    type: DELETE_ITEM,
    id
  }
}

/components/Item.jsx

export default class Item extends React.Component {

renderDelete = () => {
    return <button onClick={this.props.onDelete}>x</button>
  };

  renderItem = () => {
    const onDelete = this.props.onDelete

    return (
      <div onClick={this.edit}>
        <span>{this.props.text}</span> {onDelete ? this.renderDelete() : null}
      </div>
    )
  }

/components/Items.jsx

export default class Items extends React.Component {


  handleOnDelete = (id) => {
    this.props.dispatch(actions.deleteItem(id))
  }

  render() {
    const {items, onEdit, onDelete } = this.props

    return (
      <ul>{items.map(item =>
        <li key={item.id}>
          <Item
            id={item.id}
            text={item.text}
            onEdit={this.handleOnEdit}
            onDelete={this.handleOnDelete.bind(null, item.id)}
          />
        </li>
      )}</ul>
    );
  }
}

export default connect(
  state => ({
    items: state.items
  })
)(Items)

/reducers/items.js

case types.DELETE_ITEM:
  const filteredItems = state.filter((item) => {
    item.id !== action.id
  });

  return filteredItems

我不确定为什么单击 x 按钮删除一个项目会删除所有项目。在此先感谢您的帮助

您没有 return 减速器中过滤器的值。

你应该添加 return:

const filteredItems = state.filter((item) => {
  return item.id !== action.id;
});

或者使用短版本,不带括号:

const filteredItems = state.filter((item) => item.id !== action.id);