一、安装 ruex
npm install ruex复制代码
使用:
import React, { Component } from 'react'; import { Button,Input} from 'antd'; import {connect} from 'ruex'; class App extends Component { constructor(props){ super(props) this.state={} } render() { const {total_num,isshow,numbers} = this.props return (); } } const mapStateToProps = (state)=>({//传入需要更改状态的值 total_num:state.total_num, isshow:state.isshow, numbers:state.numbers }) const mapMutationsToProps = ['add','cut'];//直接通过更改mutations改变数据 const mapActionsToProps = ['addliat','cutAsync','addPromise','isshowsAsync','change_num'];//通过action操作mutations,从而更改数据状态 export default connect( mapStateToProps, mapMutationsToProps, mapActionsToProps )(App);复制代码
在src下创建文件夹store(名字任意起) 创建 actions.js store.js mutations.js types.js
在types.js中
export const ADD_NUM = 'ADD_NUM' //增加export const CUT_NUM = 'CUT_NUM' //减少复制代码
在 mutations.js中
import * as types from './types' export const mutations={[types.ADD_NUM](state,payload){ state.total_num +=payload}[types.CUT_NUM](state,payload){ state.total_num -=payload}}复制代码
在actions.js中
import * as types from './types' export const actions = {addliat({state,commit,rootState,dispatch},payload){ commit(types.ADD_NUM,payload)},cutAsync({state,commit,rootState,dispatch},payload){ commit(types.CUT_NUM,payload)} }复制代码
在store.js中
import {createStore} from 'ruex'import {mutations} from './mutations'import {actions} from './actions' const state={total_num:50} //中间件打印cosnt logger = (state)=>(next)=>(mutations,payload)=>{console.group('改变mutations之前',store.getState())next(mutations,payload)console.group('改变mutations之后',store.getState())} const store =createState({ state,mutations,actions},[logger])export default store 复制代码
最后在主页使用index.js
import React from 'react';import ReactDOM from 'react-dom';import {Provider} from 'ruex'; //1import store from './store/store'//2import App from './App';//3import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(//4 , document.getElementById('root'));registerServiceWorker();复制代码