gpt4 book ai didi

javascript - 我无法通过在React Native中单击redux来从FlatList中一一删除项目

转载 作者:行者123 更新时间:2023-12-02 21:32:45 26 4
gpt4 key购买 nike

我创建了一个简单的购物应用程序,它具有三个屏幕,包括:HomeBook StoreCart 屏幕

我正在使用 redux 来更新所有状态,除了一件事之外,一切都运行顺利。我希望用户在点击 Cart 中的项目时,它们会被一一删除,但问题是,当我单击一个项目时,所有项目都会同时被删除

我该如何解决这个问题?

reducer 代码:


import {
ADD,
REMOVE


} from '../actions/types';



const initialState = {

items: [],
counter: 0
}



export const cardReducer = (state = initialState, action) => {

switch (action.type) {
case ADD:
return {
...state, items: state.items.concat({

name: action.payload.name,
index: Math.random(),
price: action.payload.price,
id: action.payload.id



}), counter: state.counter + 1 }
break;
case REMOVE:
return {
...state,
items: state.items.filter((item) => {

item.index !== action.payload

}), counter: state.counter - 1 }

break;

default:
return state;
}}

操作代码:

import {
ADD,
REMOVE


} from './types';


export const addSomething = (item) => {

return {

type: ADD,
payload: item

}}


export const removeSomething = (index) => {

return {


type: REMOVE,
payload: index
} }

这是购物车屏幕代码:

import { useDispatch, useSelector } from 'react-redux';
import { addSomething, removeSomething } from '../actions';




const Cards = (props) => {


const { navigation } = props;
const dispatch = useDispatch();
const items = useSelector(state => state.cardR.items)



return (


<View style={{ alignItems: 'center', flex: 1 }}>
<View style={{ width: '80%' }}>
<FlatList
data={items}
keyExtractor={(item, index) => index}
renderItem={({ item, index }) => (

<TouchableOpacity
style={styles.button}
activeOpacity={0.7}
onPress={(index) => dispatch(removeSomething(item.index))}

>

<Text style={{ color: 'white' }}>{item.name}</Text>
<Text style={{ color: 'white' }}>{item.price}</Text>

</TouchableOpacity>

)} />
</View>
</View>


)}

最佳答案

问题出现在 index 属性中,同样 @giotskhada 在他的回复中也提到了。可能的解决方案是使用其 id 而不是索引来检查可移动项目,索引已经存在以唯一标识每个项目。

试试这个 -

reducer 代码:

case REMOVE:
return {
...state,
items: state.items.filter((item) => {
return item.id !== action.payload // Id instead of index and return statement
}),
counter: state.counter - 1
}

break;

购物车屏幕代码:

<TouchableOpacity
style={styles.button}
activeOpacity={0.7}
onPress={(index) => dispatch(removeSomething(item.id))}> // id instead of index

<Text style={{ color: 'white' }}>{item.name}</Text>
<Text style={{ color: 'white' }}>{item.price}</Text>

</TouchableOpacity>

关于javascript - 我无法通过在React Native中单击redux来从FlatList中一一删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60579098/

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