Home >Web Front-end >JS Tutorial >Specific steps to use Vuex in React

Specific steps to use Vuex in React

php中世界最好的语言
php中世界最好的语言Original
2018-04-08 14:26:211549browse

This time I will bring you the specific steps for using Vuex in React. What are the precautions for using Vuex in React? Here are practical cases, 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:

  1. state: store data

  2. mutations: change state The only way is to submit a mutation

  3. 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=&#39;&#39;>
 <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:

  1. mapStateToProps: Bind the data on the state to the current component on props.

  2. 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.

  3. 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:

How to use slots/scoped slots in Vue

The use of slot sockets in vue components Detailed explanation

The above is the detailed content of Specific steps to use Vuex in React. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn