美文网首页
redux 项目搭建

redux 项目搭建

作者: 金字笙调 | 来源:发表于2017-07-24 19:49 被阅读0次

环境目录

  • Routes.js (这里放置路由组件,同时使用redux 将所有组件包裹起来,形成一个state树, 数据放在store中
  • redux
    • reducer
      • number.js (其中一个reducer
      • index.js ( ....combineReducers, 统一所有reducer到一个入口
    • action ( 放置一些通用的方法,在这里可以使用dispatch触发一些函数
    • store.js ( 引入reducer和其他一些中间件)
  • App.js ( 组件)

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);

相关文章

网友评论

      本文标题:redux 项目搭建

      本文链接:https://www.haomeiwen.com/subject/mgcmkxtx.html