Introduction
We have learned Redux on Day 12 (useSelect and useDispatch).
However, it's complex to connect the child component with actions and states. We can use useSelect and useDispatch to connect the child component with global states.
Roles
1.Reducer and actions
- As same as Day 12
const { combineReducers } = Redux;
//types
const GET_PRODUCTS = 'GET_PRODUCTS';
//reducer
const initState = {
products: [],
}
const ShoppingCartReducer = (state = initState, action) => {
switch(action.type) {
case GET_PRODUCTS:
return {
...state,
products: action.payload
}
default:
return state;
}
}
const rootReducer = combineReducers({
products: ShoppingCartReducer
});
//action
const getProducts = () => ({
type: GET_PRODUCTS,
payload: [{
category: 'food',
name: 'noodles',
size:'large',
price:100
},{
category: 'food2',
name: 'noodles',
size:'small',
price:50
},{
category: 'food',
name: 'rice',
size:'large',
price:120
}]
});
2.store
- As same as Day 12
const { createStore } = Redux;
//store
const store = createStore(
rootReducer
);
3.Provider and the parent component
- As same as Day 12
const { Provider} = ReactRedux;
const app = (
<Provider store={ store }>
<ContentContainer/>
</Provider>
);
4.The child component and useSelect, useDispatch
const { useDispatch, useSelector } = ReactRedux;
const selectProducts = (rootState) => rootState.products.products;
//child component
const Content = () => {
const disPatch = useDispatch();
disPatch(getProducts());
return (
<Menu/>
)
}
const Menu = () => {
const products = useSelector(selectProducts);
return (
<div className="container menu-container">
<div className="row">
{products.map(product => (
<MenuItem product = {product}/>
))}
</div>
</div>
)
}
Implementations
Articles
There are some of my articles. Feel free to check if you like!
- My blog-posts for software developing: https://medium.com/a-layman
- My web resume: https://jenhsuan.github.io/ALayman/cover.html
- Facebook page: https://www.facebook.com/imalayman
Top comments (0)