用最简单的方式,了解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...欢迎同窗们跟我一块儿讨论。

相关文章
相关标签/搜索