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:
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> <child1></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> </p><p> total_num: {total_num} </p> <button>mutation:add</button> <button>action:addAsync</button> <button>action:addPromise</button> <br> <button>mutation:double</button> <button>action:doubleAsync</button> <button>action:doublePromise</button> ) } } 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 current component on props.
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:
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!

在react中,canvas用于绘制各种图表、动画等;可以利用“react-konva”插件使用canvas,该插件是一个canvas第三方库,用于使用React操作canvas绘制复杂的画布图形,并提供了元素的事件机制和拖放操作的支持。

在react中,antd是基于Ant Design的React UI组件库,主要用于研发企业级中后台产品;dva是一个基于redux和“redux-saga”的数据流方案,内置了“react-router”和fetch,可理解为应用框架。

React不是双向数据流,而是单向数据流。单向数据流是指数据在某个节点被改动后,只会影响一个方向上的其他节点;React中的表现就是数据主要通过props从父节点传递到子节点,若父级的某个props改变了,React会重渲染所有子节点。

因为在react中需要利用到webpack,而webpack依赖nodejs;webpack是一个模块打包机,在执行打包压缩的时候是依赖nodejs的,没有nodejs就不能使用webpack,所以react需要使用nodejs。

在react中,forceupdate()用于强制使组件跳过shouldComponentUpdate(),直接调用render(),可以触发组件的正常生命周期方法,语法为“component.forceUpdate(callback)”。

react是组件化开发;组件化是React的核心思想,可以开发出一个个独立可复用的小组件来构造应用,任何的应用都会被抽象成一颗组件树,组件化开发也就是将一个页面拆分成一个个小的功能模块,每个功能完成自己这部分独立功能。

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

react和reactdom的区别是:ReactDom只做和浏览器或DOM相关的操作,例如“ReactDOM.findDOMNode()”操作;而react负责除浏览器和DOM以外的相关操作,ReactDom是React的一部分。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools
