This time I will bring you the tips for using Reac Vuex, and what are the precautions for using Reac Vuex. The following is a practical case, let’s take a look.
I have always been a loyal fan of Redux, but after using Vuex, I lamented how quickly I got started with Vuex, so I came up with the idea of writing a Vuex-like library that can be used in React, temporarily named Ruex.
How to use
1: Create a Store instance:
Same as vuex, use a single The state tree (an object) contains all application-level states (store).
store can configure state, mutations, actions and modules attributes:
state: store data
mutations: change state The only way is to submit a mutation
actions :Action submits a mutation instead of directly changing the state. Action can contain any asynchronous operation, trigger mutations, and trigger other actions.
Support middleware: middleware will be executed before and after each mutation is triggered.
store.js:
import {createStore} from 'ruex' const state = { total_num:1111, } const mutations = { add(state,payload){ state.total_num += payload }, double(state,payload){ state.total_num = state.total_num*payload }, } const actions = { addAsync({state,commit,rootState,dispatch},payload){ setTimeout(()=>{ commit('add',payload) },1000) }, addPromise({state,commit,rootState,dispatch},payload){ return fetch('https://api.github.com/search/users?q=haha').then(res=>res.json()) .then(res=>{ commit('add',1) dispatch('addAsync',1) }) }, doubleAsync({state,commit,rootState,dispatch},payload){ setTimeout(()=>{ commit('double',2) },1000) }, doublePromise({state,commit,rootState,dispatch},payload){ return fetch('https://api.github.com/search/users?q=haha').then(res=>res.json()) .then(res=>{ commit('double',2) dispatch('doubleAsync',2) }) }, } // middleware const logger = (store) => (next) => (mutation,payload) =>{ console.group('before emit mutation ',store.getState()) let result = next(mutation,payload) console.log('after emit mutation', store.getState()) console.groupEnd() } // create store instance const store = createStore({ state, mutations, actions, },[logger]) export default store
Bind the Store instance to the component
ruex provides Provider to facilitate store instance registration to the global context. Similar to react-redux.
App.js:
import React from 'react' import {Provider} from 'ruex' import store from './store.js' class App extends React.Component{ render(){ return ( <Provider store={store} > <Child1/> </Provider> ) } }
Use or modify the data on the store
After the store binding is completed, in the component You can use the data on the state and modify the state by triggering mutations or actions. For specific methods, please refer to the binding method of react-redux: using connect high-order components.
Child1.js:
import React, {PureComponent} from 'react' import {connect} from 'ruex' class Chlid1 extends PureComponent { state = {} constructor(props) { super(props); } render() { const { total_num, } = this.props return ( <p className=''> <p className=""> total_num: {total_num} </p> <button onClick={this.props.add.bind(this,1)}>mutation:add</button> <button onClick={this.props.addAsync.bind(this,1)}>action:addAsync</button> <button onClick={this.props.addPromise.bind(this,1)}>action:addPromise</button> <br /> <button onClick={this.props.double.bind(this,2)}>mutation:double</button> <button onClick={this.props.doubleAsync.bind(this,2)}>action:doubleAsync</button> <button onClick={this.props.doublePromise.bind(this,2)}>action:doublePromise</button> </p>) } } const mapStateToProps = (state) => ({ total_num:state.total_num, }) const mapMutationsToProps = ['add','double'] const mapActionsToProps = ['addAsync','addPromise','doubleAsync','doublePromise'] export default connect( mapStateToProps, mapMutationsToProps, mapActionsToProps, )(Chlid1)
API:
mapStateToProps: Bind the data on the state to the props of the current component.
mapMutationsToProps: Bind mutations to props. For example: mutation can be triggered by this.props.add(data) when calling, and the data parameter will be received by the payload parameter of mutation.
mapActionsToProps: Bind actions to props.
Internal implementation
ruex internally uses immer to maintain store state updates, so in mutation, it can be modified directly An object's properties change state without returning a new object. For example:
const state = { obj:{ name:'aaaa' } } const mutations = { changeName(state,payload){ state.obj.name = 'bbbb' // instead of // state.obj = {name:'bbbb'} }, }
Supports modules (namespace is not supported yet)
Supports middleware. Note: actions have implemented functions similar to redux-thunk
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
Operation AngularJS from scratch to implement application modularization
D3.js makes a memory circle Save image
The above is the detailed content of What are the usage tips of Reac+Vuex?. For more information, please follow other related articles on the PHP Chinese website!