React JS从列表中删除特定项目

时间:2017-11-20 15:06:59

标签: javascript reactjs arraylist redux react-redux

我设法创建了一个朋友列表,并且addFriends功能正常工作,即每次按下按钮时都会添加一个名为“新朋友”的新人。

removeFriend功能也可以,但是如果我添加几个朋友然后按删除朋友它会删除键后的每个项目,而不仅仅是键本身。我希望下面的代码只删除键2(George Brown)而不是其后的所有记录。

friendsActions.js

import * as f from '../constants'

export const addFriend = ({ firstname, lastname }) => ({
  type: f.ADD_FRIEND,
  frienditem: {
    firstname,
    lastname,
  },  
})

export const removeFriend = ({ key }) => ({
   type: f.REMOVE_FRIEND,
  key,
})

friendsReducer.js

import * as f from '../constants'

const initialState = [
  { firstname: 'John', lastname: 'Smith' },
  { firstname: 'James', lastname: 'Johnson' },
  { firstname: 'George', lastname: 'Brown' },
 ]

const friendsReducer = (state = initialState, action) => {
  switch (action.type) {
    case f.ADD_FRIEND:
      return [...state, action.frienditem] 
    case f.REMOVE_FRIEND:
      console.log('removing friend with key ' + action.key)
      return [...state.slice(0, action.key), ...state.slice(action.key + 1)]
    default:
       return state
  }
 }

export default friendsReducer

index.js(常数)

export const ADD_FRIEND = 'ADD_FRIEND'
export const REMOVE_FRIEND = 'REMOVE_FRIEND'

friendsContainer.js

import React from 'react'
import Page from '../components/Page'

import FriendList from '../containers/FriendList'

import { css } from 'glamor'

const FriendContainer = props => (
  <Page title="Friends List" colour="blue">
    <FriendList {...props} />
  </Page>
)

export default FriendContainer

friendsList.js

import React from 'react'
import { css } from 'glamor'

const Friend = ({ firstname, lastname }) => (
  <div>
    <ul>
      <li>
        {firstname} {lastname}
      </li>
    </ul>
  </div>
)

const FriendList = ({ friends, addFriend, removeFriend }) => (
  <div>
    <div>
      {friends.map((frn, i) => (
        <Friend key={++i} firstname={frn.firstname} lastname={frn.lastname} />
      ))}
    </div>
    <button onClick={() => addFriend({ firstname: 'New', lastname: 'Friend' })}>
      Add Friend
    </button>
    <button onClick={() => removeFriend({ key: '2' })}>Remove Friend</button>
  </div>
)

export default FriendList

1 个答案:

答案 0 :(得分:4)

您传入一个字符串作为操作的键:

{
  key: '3'
}

然后在你的代码中,你加1,在这种情况下是'31'。

state.slice(action.key + 1)更改为state.slice(parseInt(action.key, 10) + 1)或将您的密钥从一开始就更改为数字。