roz333 :
: 나는 세 가지를 포함하여 화면이 간단한 쇼핑 응용 프로그램 만든 Home
, Book Store
및 Cart
스크린
나는 모든 상태를 업데이트 REDUX를 사용하고, 모든 것이 원활 한 가지를 제외시켰다 작품. 의 항목을 클릭 할 때 나는 사용자가 원하는 Cart
그들이 하나 제거 하나를 얻을하지만 문제는 내가 한 항목을 클릭 할 때 그들 모두가 동시에 제거 얻을 것입니다
나는이 문제를 어떻게 해결할 수 있습니까?
감속기 코드 :
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
} }
그리고 이것은이다 Cart
화면 코드 :
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>
)}
Kundan 싱 Chouhan :
문제는에 보인다 index
마찬가지로 @giotskhada 그의 반응에 언급했다 속성입니다. 가능한 솔루션은 그와 이동식 항목을 확인할 수 있었다 id
고유의 각 항목을 식별에 이미있는 색인이 아니라.
대신이 시도 -
감속기 코드 :
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>