Home>
Reduce separately
const defaultState= {
customers: []
}
export const customersReducer= (state= defaultState, action)= >
{
switch (action.type) {
case 'addCustomer':
return {... state, customers: [... state.customers, action.payload]}
case 'removeCustomer':
return {... state, customers: state.customers.filter (customer= >
customer.id!== action.payload)}
default:
return state
}
}
Code:
const App= ()= >
{
const dispatch= useDispatch ();
const customers= useSelector (state= >
state.customers.customers)
const addCustomer= (name)= >
{
const customer= {
name,
id: Date.now (),
}
dispatch ({type: 'addCustomer', payload: customer})
}
const removeCustomer= (customer)= >
{
dispatch ({type: 'removeCustomer', payload: customer.id})
}
return (
<
div style= {{display: 'flex', justifyContent: 'center', flexDirection: 'column'}} >
<
div style= {{display: 'flex', justifyContent: 'center', margin: '20px 0'}} >
<
div >
<
button onClick= {()= >
addCustomer (prompt ())} >
Add client <
/button >
<
/div >
<
/div >
{customers.length >
0?
<
div >
{customers.map (customer= >
<
div onClick= {()= >
removeCustomer ()} >
{customer.name} <
/div >
)}
<
/div >
:
<
div style= {{display: 'flex', justifyContent: 'center'}} >
No clients
<
/div >
}
<
/div >
);
};
export default App;
-
Answer # 1
Pass to the function when calling the customer itself
< div > {customers.map (customer= > < div onClick= {()= > removeCustomer (customer)} > {customer.name} < /div > )} < /div >
-
Answer # 2
Pass to the function when calling the customer itself
< div > {customers.map (customer= > < div onClick= {()= > removeCustomer (customer)} > {customer.name} < /div > )} < /div >
Related questions
- javascript : Is it possible to use the same state for different elements of an array?
- javascript : React + Redux why element is not updated when store is updated
- javascript : How to optimize useSelector redux
- javascript : Why do we need redux middleware?
- reactjs : What does line 15 mean?
- javascript : How to sort an array by date so that the oldest ones come first
- javascript : Date display bug in React
- javascript : React. Unloading ads for 10 pieces
- javascript : How to restart an existing React app?
- javascript : The simplest code on React.js does not work
Please clarify your specific problem or provide more detailed information on what exactly you need. As it stands, it is difficult to know exactly what you are asking.
Дух сообщества2021-12-20 13:15:06