redux

redux核心概念: store,state,action,reducer

首先通过reducer新建store,通过store.getState()获取状态

需要状态变更,store.dispatch(action) 来修改

reducer函数接受state和action,返回新的state,可以用store.subscribe监听每次的修改

import { createStore } from 'redux'

function reducer(state=10, action){
  switch (action.type) {
      case 'ADD':
        return state + 1
      case 'CUT':
          return state - 1
      default:
          return 10
  }
}

// 创建一个store createStore中传入的必须是一个函数
let store = createStore(reducer)
let init = store.getState()
console.log('一开始数据------', init)

function listener() {
    let cur = store.getState()
    console.log('cur------', cur)
}

// 订阅,每次state修改,都会执行listener
store.subscribe(listener)

//提交状态变更
store.dispatch({type: 'ADD'})
store.dispatch({type: 'ADD'})
store.dispatch({type: 'CUT'})

redux如何跟react一起使用

index.js中

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { createStore } from 'redux'
import {counter, add, cut} from './redux'

const store = createStore(counter)

function init (){
    ReactDOM.render(<App
            store={store}
            add={add}
            cut={cut}
        />,
        document.getElementById('root')
    );
}
init ()

store.subscribe(init)
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
        let store = this.props.store
    return (
      <div className="App">
          <h3>redux中默认的store.getState()的值为
              <span>{store.getState()}</span>
          </h3>
        <button onClick={()=>{
            store.dispatch(this.props.add())
        }}>按钮 + 1</button>
        <button onClick={()=>{
            store.dispatch(this.props.cut())
        }}>按钮 - 1</button>
      </div>
    );
  }
}

export default App;

 

posted @ 2019-04-01 17:53  慕斯undefined  阅读(112)  评论(0编辑  收藏  举报