用最簡單的方式,瞭解react全家桶之redux

本文以create-react-app項目做爲開端,從最基礎代碼成長爲一個實際項目的過程。
注意:本文沒有大部分理論,只有代碼,會逐步延伸。css

clipboard.png

redux組成部分

createStore.js
reducer.js
action.js react

1.咱們來講說第一個,createStore.jsgit

先看看代碼github

import { createStore } from 'redux'
import reducer from ‘./reducer’
export default () => {
    let store = createStore(reducer)
    return store
}

是否是炒雞簡單?
從redux裏獲取建立的方法,而後建立store的目的是幹什麼?固然是修改reducer,咱們把reducer看成一個參數傳入。redux

2.接着,咱們看看咱們的reducer是幹什麼的,看代碼app

function counter(state = {value : 0}, action) {
  switch (action.type) {
    case 'INCREASE':
      return Object.assign({}, state, {
        value: state.value + 1
      })
    case 'DECREASE':
        return Object.assign({}, state, {
        value: state.value - 1
      })
    default:
      return state
  }
}

export default counter

是否是也炒雞簡單,無非就是修改一個state的value參數!這個state是帶默認值。dom

那咱們要怎麼觸發修改呢?ide

沒錯,那就是發起action。svg

3.action.js到底幹了些什麼?函數

import { bindActionCreators } from 'redux'

export const INCREASE = 'INCREASE'
export const increase = () => ({ type: INCREASE})

export const DECREASE = 'DECREASE'
export const decrease = () => ({ type: DECREASE})

export const containerActions = dispatch => bindActionCreators({
  increase,
  decrease
}, dispatch)

bindActionCreators: 是由redux提供的輔助函數
參數由{x,y}:action,dispatch:store實例提供

好了好了,到此,咱們就把一個完整的redux流程寫完了。
就這麼簡單,如今咱們來看看把這坨代碼扔到create-react-app初始化完的代碼裏,是否是能運行起來。

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { connect } from 'react-redux'
import { containerActions } from './action'

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
        <button onClick={ this.props.increase }>INCREASE</button><br/>
        <button onClick={ this.props.decrease }>DECREASE</button><br/>
        <p>VALUE: {this.props.value}</p>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    value: state.value
  }
}
//connect是由react-redux提供的輔助函數,做用是將store state裏的值,映射到this.props
//containerActions是把action裏的方法綁定到當前組件,也就是App的this.props
export default connect(mapStateToProps, containerActions)(App);

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { Provider } from 'react-redux'
import createStore from './createStore'

let store = createStore()
//經過Provider把store傳遞到react
ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>, 
    document.getElementById('root'));
registerServiceWorker();

完美運行。
github:https://github.com/NatPagle/m...歡迎同窗們跟我一塊兒討論。

相關文章
相關標籤/搜索