redux 项目搭建

2017-07-24  本文已影响0人  金字笙调

环境目录

Routes.js

import React from 'react'
import App from './App'
import { Provider } from 'react-redux'
import Store  from './redux/store'

const Routes = () =>(
  <Provider store={Store}>
    <App />
  </Provider>
)


export default Routes

store.js

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import promiseMiddleware from 'redux-promise-middleware';
import logger from 'redux-logger';

import rootReducer from './reducer/index';

 const Store = createStore(
  rootReducer,       //所有reducers方法的集合
  applyMiddleware(promiseMiddleware(), thunk, logger)  //引入中间件
);

export default Store;

reducer/index

import { combineReducers } from 'redux';
import Numbers from './number';
import Age from './age';

const rootReducer = combineReducers({    //把所有reducer函数都集中到这里
  Numbers,
  Age
});


export default rootReducer

reducer/age

const initState = {age: 1, count: 100}

function Age(state = initState, action){
  switch(action.type){
    case 'ADD_AGE_FULFILLED':   //在后文中,我们的action.type是ADD_AGE,在这里被执行的原因是我们使用了中间件redux-promsie-middleware 的原因
    return {...state, age:state.age+1 }
    case 'SUB_AGE':
    return { ...state, age:state.age-1 }
    default:
    return state
  }
}


export default Age

reducer/numer

const initState = {num: 1}

function Numbers(state = initState, action){
  return state
}


export default Numbers

App.js

import React, { Component } from 'react';
import { connect }  from 'react-redux'

import './App.css';

class App extends Component {
  componentWillMount(){
    console.log(this.props.age)
  }

  add = (val) =>{ this.props.dispatch( {   //测试  redux-promise-middleware
     type:"ADD_AGE" ,
     payload: new Promise(reslove => setTimeout(() => reslove(), 5000))
   })
  }

  inc = () =>{ this.props.dispatch( { type:"SUB_AGE" } ) }

  render() {
    const { age, count } = this.props.age
    return (
      <div className="App">
            <span>{ age }</span>
            <button onClick={this.add.bind(this, age)} key = {1}>+</button>
            <button onClick={this.inc.bind(this)} key = {2}>-</button>
            <span>{ count }</span>
      </div>
    );
  }
}


function mapStateToProps(state){  //从store中取出想要的值
  return  { age: state.Age }
}

export default connect(mapStateToProps)(App);
上一篇 下一篇

猜你喜欢

热点阅读