gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 14:42:48 25 4
gpt4 key购买 nike

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

removeFriend 功能也可以使用,但如果我添加几个 friend 然后按“删除 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

最佳答案

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

{
key: '3'
}

然后在代码中添加 1,在本例中为“31”。

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

关于javascript - React JS从列表中删除特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47395063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com