使用React Native Redux保持数组,并使用联合减缩器添加或删除项



我写React已经有一段时间了。在我的应用程序中,有一个带有http请求的表单,如果响应成功,我需要保留这些参数。我还给出了条件,并根据这些参数组织最平坦的。我正试图用redux数组保留这些参数。然而,我在redux数组中添加了这些参数,但无法删除。我在哪里调用删除函数?我在下面留下了代码。请帮帮我。

//actions.js 
export const ADD_LIST='ADD_LIST'; // add to redux list
export const DELETE_LIST='DELETE_LIST'; //delete redux list 
export const add_List = (list) => {
return { type: ADD_LIST, payload: list };
};
export const delete_List = (item) => {
return { type: DELETE_LIST, payload:item};
};
//rootReducer.js
import {combineReducers} from "redux";
import {userReducer} from "./userReducer";
import {listReducer} from "./listReducer";
export default combineReducers({
userState:userReducer,
ListState:listReducer,
})
//listReducer.js
import {ADD_LIST} from "./actions";
import {DELETE_LIST} from "./actions";

const INITIAL_STATE={
list:[]
}
export function listReducer(state=INITIAL_STATE,action){
switch (action.type){
case 'ADD_LIST':
return{...state,
list:[...state.list,action.payload]
};
case 'DELETE_LIST':
return{
list:[
...state.list.filter(item=>item!==action.payload) //I don't know if it is true?
]
}
default:
return state;
}
}
//Http Request
if (xmlhttp.responseText.includes("S0000")) {
Alert.alert("Success", "Success. ", [
{text: 'OK', onPress: () => exitAction()},

],
{cancelable: true}
)
setData(oldArray => [...oldArray, {id: id, date: date}]) //if the result is successful, i set user's id and date to a state that has name data
dispatch(ADD_LIST(data));
}

<FlatList
renderItem={({item,index})=> {
let count=0;
data?.map((userData)=>{
if(userData.id===item.id&&userData.date===moment().format('DD-MM-   YYYY')).{ //I want if this condition not met, delete the item redux array.
count+=1;
}
})
return(
<View style={[styles.flatlistInnerContainer,count!==0&&{backgroundColor:'rgba(108,210,147,0.62)'}]}></View>
)        
})
/>

//I also want visible filter for the redux array. I dont work with redux toolkit or slice. Please Help me.

数据看起来有一个id属性,您应该使用它来唯一标识要从数组中删除的数组元素对象。

示例对象:{ id, date }

删除项目dispatch(delete_List(item));,其中item是整个对象。

减速机逻辑:

case 'DELETE_LIST':
return {
...state, // <-- shallow copy state
list: state.list.filter( // <-- filter creates new array reference
item => item.id !== action.payload.id
),
}

相关内容

  • 没有找到相关文章

最新更新