Introduction
- I have ever used React context APIs to create global states on Day2(https://dev.to/jenhsuan/day-2-of-100daysofcode-create-a-reactjs-global-states-manager-with-react-hooks-3c4b)
- Today I tried to use Redux to do the same thing
Introduction to Context APIs
Installation
npm i -S redux react-redux redux-thunk redux-devtools-extension
There are few roles from Redux and React-Redux libray
1.Reducer and actions
- The reducer and actions here do the same thing as the state in React Context APIs.
- The reducer has to receive the action. It changes the state depends on the type of action.
const { combineReducers } = Redux;
//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
//Get products
const bindActionsToDispatch = dispatch => ({
getProducts: (data) => dispatch({
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
- In Redux, we inject reducers to store
const { createStore } = Redux;
//store
const store = createStore(
rootReducer
);
3.Provider and the parent component
- In Redux, we inject store to store
- We integrate Provider with the parent component
const { Provider} = ReactRedux;
const app = (
<Provider store={ store }>
<ContentContainer/>
</Provider>
);
4.connect and the child component
const { connect } = ReactRedux;
const bindActionsToDispatch = dispatch => ({
getProducts: (data) => dispatch({
type: GET_PRODUCTS,
payload:...
})
})
//child component
const Content = ({products: {products}, getProducts}) => {
React.useEffect( ()=>{
getProducts();
}, []);
return (
...
)
}
const mapStateProps = state => ({
products: state.products
});
const ContentContainer = connect( mapStateProps, bindActionsToDispatch)(Content);
These is a simple digram for React components and Context APIs.
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)