天天看點

react結合 antd redux的簡單使用

// AntdTest 測試 redux 元件
// 在src/index.js檔案中 import 'antd/dist/antd.css' 安裝 antd 的指令 npm install antd --save
import React, { Component } from 'react'
import { Button, Pagination, List, Input    } from 'antd';
import store from '../store'

export default class AntdTest extends Component {
  constructor(props) {
    super(props)
    console.log(store, 'store')
    this.state = store.getState();
    store.subscribe(this.storeChange) // 訂閱 Redux的狀态---> 解決store裡的資料已經更新了,但是元件還沒有進行更新
    console.log(this.state)
  }
  // 輸入框 change 事件
  changeValue = e => {
    // console.log(e.target.value);
    const action = {
      type:'changeInput',
      value:e.target.value
    }
    store.dispatch(action)
  }
  // 更新store
  storeChange = () => {
    this.setState(store.getState())
  }
  // 添加條目功能
  addItem = () => {
    const action = { type:'addItem'}
    store.dispatch(action)
  }
  // 删除條目功能
  deleteItem = (index) => {
    console.log(this,'this')
    const action = {
      type:'deleteItem',
      index
    }
    store.dispatch(action)
  }
  // 渲染函數
  render() {
    return (
      <div className="antd-box">
        <div>store裡面的資料name:{this.state.name}</div>
        <Input 
          placeholder='請添加' 
          style={{ width:'250px', marginRight:'10px'}}
          onChange={this.changeValue}
        />
        <Button type="primary" onClick={this.addItem}>添加條目</Button>
        <div style={{margin:'10px',width:'300px'}}>
          <List
            bordered
            dataSource={this.state.testList}
            renderItem={(item, index)=>(<List.Item onClick={(index) => this.deleteItem(index)}>{item}</List.Item>)}
          />    
        </div>
        <Pagination defaultCurrent={1} total={50} />
        <Button type="primary">Primary</Button>
        <Button>Default</Button>
        <Button type="dashed">Dashed</Button>
        <Button type="link">Link</Button>
      </div>
    )
  }
}      
// store/index檔案  如果你要使用中間件,就必須在redux中引入applyMiddleware
import { createStore, applyMiddleware, compose   } from 'redux';
// import thunk from 'redux-thunk'
import reducer from './reducer'    
import mySaga from './mySaga'
import createSagaMiddleware from 'redux-saga'   //引入saga
const sagaMiddleware = createSagaMiddleware();   //建立saga中間件

// 使用Chrome浏覽器安裝插件,在浏覽器右上角有三個點,然後點選"更多工具",再點選"擴充程式",再點選右側的"打開Chrome網上商店",然後搜尋Redux DevTools 直接安裝;(FQ工具)
// 配置Redux Dev Tools插件 控制台調試倉庫資料
// const store = createStore(reducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
// redux-thunk 要和 Redux Dev Tools插件一并使用了,需要使用增強函數。使用增加函數前需要先引入compose
// Redux的中間件  redux-thunk Redux-saga
const composeEnhancers =   window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose

// const enhancer = composeEnhancers(applyMiddleware(thunk)) // 如果你想用 redux-thunk

const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware)) // 如果你想用 redux-saga

const store = createStore(reducer, enhancer) // 建立資料存儲倉庫

// then run the saga
sagaMiddleware.run(mySaga)

export default store

// 官方寫法
// const store = createStore(
//   reducer,
//   applyMiddleware(thunk)
// )      
// store/reducer.js 檔案 預設資料 Reducer裡隻能接收state,不能改變state
const initState = {
  testList:[
    'vue',
    'react'
  ],
  inputValue: '請輸入内容',
  name: 'redux'
}  
// state: 指的是原始倉庫裡的狀态。
// action: 指的是action新傳遞的狀态
// Reducer裡編寫業務邏輯
export default (state = initState, action) => {  //就是一個方法函數
  console.log(state,'redux-state',action,'redux-action')
  if (action.type === 'changeInput') {
    let newState = JSON.parse(JSON.stringify(state)) // 深度拷貝state
    newState.inputValue = action.value
    return newState
  }
  //根據type值,編寫業務邏輯
  if (action.type === 'addItem' ) { 
    let nState = JSON.parse(JSON.stringify(state)) // 新增
    console.log(nState,'nState')
    nState.testList.push(nState.inputValue);
    // nState.inputValue = '';
    return nState
  }
  if (action.type === 'deleteItem' ) { 
    let newState = JSON.parse(JSON.stringify(state)) 
    newState.testList.splice(action.index,1)  //删除
    return newState
  }
  return state
}