【问题标题】:React JS Removing specific item from listReact JS从列表中删除特定项目
【发布时间】:2018-05-03 20:27:09
【问题描述】:

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

removeFriend 功能也可以,但是如果我添加几个朋友然后按 Remove Friend,它会删除键之后的每个项目,而不仅仅是键本身。我希望下面的代码只删除键 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

【问题讨论】:

    标签: javascript reactjs arraylist redux react-redux


    【解决方案1】:

    您正在传递一个字符串作为操作的键:

    {
      key: '3'
    }
    

    然后在您的代码中,将其加 1,在本例中为 '31'。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-08
      • 2019-03-17
      • 1970-01-01
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多