【发布时间】: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