vue : state mutation action module
redux: state reducer action conbine合并reducer
第一步:我們在login組件中創(chuàng)建一個redux.js
const initState ={
isLogin:false,
usename:"李白"
}
export const updateLogin=(payload)=>{
return {
type:"LOGIN_UPDATE_LOGIN",
payload
}
}
export const updateUsename=(payload)=>{
return {
type:"LOGIN_UPDATE_USENAME",
payload
}
}
export default (state=initState,action)=>{
let {type}=action
switch(type){
case 'LOGIN_UPDATE_LOGIN':
return{
...state,
isLogin:action.payload
}
case 'LOGIN_UPDATE_USENAME':
return{
...state,
usename:action.payload
}
default :
return state
}
}
第二步:在cart組件中創(chuàng)建redux.js
const initState ={
cartNum:0
}
export const updateCartNum=(paylog)=>{
return {
type:"CART_UPDATE_CARTNUM",
paylog
}
}
export default (state=initState,action)=>{
let {type}=action
switch(type){
case 'CART_UPDATE_CARTNUM':
return{
...state,
cartNum:action.paylog
}
default :
return state
}
}
第三步:在src的目錄下創(chuàng)建一個redux的文件
這個用于對各個組件中的redux的模塊進行集中管理
import { combineReducers,createStore } from "redux";
//導入模塊
import cartReducer from '../pages/cart/redux'
import loginReducer from '../pages/login/redux'
//把模塊都存放到reduces
const reduces =combineReducers({
login:loginReducer,
cart:cartReducer
})
const store =createStore(reduces)
export default store;
第四步:在全局的index.js中進行掛載
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
//1.導入react-redux
import { Provider } from "react-redux";
//2.導入redux的模塊
import store from '../src/redux/redux'
ReactDOM.render(
//3.然后用Provider包住 <App />测暗,Provider里面是我們的redux的模塊
<Provider store={store}>
<App />
</Provider>
, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
第五步:在我們需要的模塊中去使用宋彼,例如cart模塊
import React from 'react';
//1.導入react-redux
import { connect } from "react-redux";
//2.導入redux
import { bindActionCreators } from "redux";
//3.導入updateLogin疏之,這個是我們模塊中定義的方法
import {updateLogin} from '../login/redux';
class My extends React.Component{
constructor(props) {
super(props);
this.login=this.login.bind(this)
}
render() {
let {isLogin}=this.props
console.log("isLogin",isLogin)
return (
<div>
{isLogin?<p>李白</p>:<button onClick={this.login}>立即登錄</button>}</div>
)
}
////////////////////修改username
login(){
setTimeout(() => {
this.props.updateLogin(true);
}, 2000);
}
}
// export default My;
// 4.把state的值放入props
function mapStateToProps(state) {
return {
isLogin: state.login.isLogin
};
}
// 5.把action放入props作儿,注意:這里的updateLogin要與我們上面導入的updateLogin一致
function mapDisapatchToProps(dispatch) {
return {
updateLogin: bindActionCreators(updateLogin, dispatch)
};
}
// 6.把Center組件變成高階組件(放入一個組件,得到一個新組件)
export default connect(mapStateToProps, mapDisapatchToProps)(My);