reduxプロジェクト構築

2986 ワード

環境ディレクトリ
  • Routes.js(ここではルーティングコンポーネントを配置し、reduxを使用してすべてのコンポーネントを包み、storeにデータを置くstateツリーを形成する)
  • redux
  • reducer
  • number.js(reducerの1つ)
  • index.js(....combineReducers、すべてのreducerを1つのエントリに統合)
  • 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 = () =>(
      
        
      
    )
    
    
    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 (
          
    { age } { count }
    ); } } function mapStateToProps(state){ // store return { age: state.Age } } export default connect(mapStateToProps)(App);