2017-11-20 7 views
0

私は友達のリストを作成することができ、addFriends機能が正しく機能します。つまり、ボタンを押すたびに「New Friend」という新しい人物が追加されます。React JSリストから特定のアイテムを削除する

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 

答えて

4

あなたは、アクションのためのキーとして文字列を渡しています

{ 
    key: '3' 
} 

次に、あなたのコードでは、あなたがこれに1を加えます。この場合は '31'です。

state.slice(action.key + 1)からstate.slice(parseInt(action.key, 10) + 1)に変更するか、キーを取得から番号に変更してください。

+0

ありがとう、これはルーキーミスハハの作品です。 – H1ggsy

関連する問題