react - redux/react-redux/redux-saga/mobx

redux 用法

1、安装 redux

yarn add redux

2、创建一个store.js文件

import { createStore } from 'redux'
// 创建reducer
function couter (state, action) {
  switch(action.type){
    case 'INCREMENT': return state + 1;
    case 'DRCREMENT': return state - 1;
    default: return state;
  }
}
// 创建 store
const store = createStore(couter)
// 暴露 store
export default store

3、index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import store from './store'

function render (){
  ReactDOM.render(
    ,
    document.getElementById('root') 
  );
}
// 调整render的方式
render()
// 订阅 store
store.subscribe(render)

serviceWorker.unregister();

4、TestStore.js 使用 store

import React, { Component } from 'react'
import { Button } from 'antd'
import store from './store'

export default class TestStore extends Component {
  increment(){
    store.dispatch({
      type: 'INCREMENT'
    })
  }
  drcrement(){
    store.dispatch({
      type: 'DRCREMENT'
    })
  }
  render() {
    return (
      

{store.getState()}

) } }

5、在app.js里面引入TestStore

import React, { Component } from 'react';
import './App.css'
import TestStore from './TestStore'
class App extends Component {
  render() {
    // let self = this
    return (
      
); } } export default App;

以上是 redux 的用法,显而易见你每次对 store 进行 dispatch(action) 都会触发 subscribe 注册的函数调用比较麻烦,其实就类似于 vuecomputed
每个应用只能有一个state,但是可以拥有多个reducers,多个reducers可以使用 combineReducers

你可能感兴趣的:(react.js,redux,mobx,redux-saga)