react-redux実戦メモ

3122 ワード

reduxはとても役に立つはずです.勉強するのは大変だが、勉強する価値がある.私は勉強したノートに基づいて、忘れないようにしました.
まず、サードパーティ製プラグイン依存をインストールするには、主に次のようにします.
第1:yarn add redux react-reduxこれは2つで、1つはreduxで、1つはreactに対するreduxである.
第二:yarn add redux-thunkこれは中間品で、とても使いやすいと言われています.
第三:yarn add babel-plugin-transform-decorators-legacy装飾器、開発する時、あなたにきれいで優雅なコードを開発させることができます.
ところで、ブラウザプラグインをもう1つインストールしたほうがいいです.[redux-devtoolsダウンロード]
最初はpackage.jsonから話しましょう.まず装飾器のプラグインを配置します.すなわち,次のpluginsの1行のコードを追加する.
"babel": {
    "presets": [
      "react-app"
    ],
    "plugins":["babel-plugin-transform-decorators-legacy"]
  },

次にindex.jsを改造します.createStoreは新しいstoreを作成するために使用され、applyMiddleware()はミドルウェアを装飾し、composeは接続パラメータ用です.
thunkはredux−thunkミドルウェア曝露の唯一の方法である.
Provider,connectはreact接続reduxの2つの新しいインタフェースです.Providerもコンポーネントを1回だけ、最外層に置いてstoreを渡します.
counterはindex-reduxに自分で書いたreducer関数の方法です.Windows.devToolsExtensionはブラウザプラグイン用の関数です.
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore,applyMiddleware,compose } from 'redux'
import thunk from 'redux-thunk'
import { Provider } from 'react-redux'

import App2 from './app2'
import { counter } from './index-redux'

const store = createStore(counter,compose(
  applyMiddleware(thunk),
  window.devToolsExtension ? window.devToolsExtension():f=>f)
)


ReactDOM.render(
  (
      
  ),
  document.getElementById('root')
);

reducerの関数は、プロジェクトに基づいて自分のものを書けばいいです.ケースを残す
const add_Gun = "Add_Gun"
const remove_Gun = "Remove_Gun"


export function counter(state=0,action){
  switch(action.type){
      case 'Add_Gun':
          return state+1
      case 'Remove_Gun':
          return state-1
      default :
          return 10
  }
}

export function Add_Gun(){
  return {type:add_Gun}
}

export function Remove_Gun(){
  return {type:remove_Gun}
}

//     ,           。
export function Add_Gun_Async(){
  return dispatch=>{
      setTimeout(()=>{
          dispatch(Add_Gun())
      },2000)
  }
}

Appコンポーネントの内容については、自分の内容に違いありません.一つのケースも残っています
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Add_Gun,Remove_Gun,Add_Gun_Async } from './index-redux'


@connect(
    // @      babel-plugin-transform-decorators-legacy   。
    //      ,  state      props  
    state=>({num:state}),
    //       ,    props ,  dispatch
    { Add_Gun,Remove_Gun,Add_Gun_Async }
    )
class App2 extends Component{
    render(){
        return(
            

{this.props.num}

) } } export default App2