美文网首页
redux-saga中间件的使用

redux-saga中间件的使用

作者: coffee1949 | 来源:发表于2019-07-14 11:17 被阅读0次
  • 1.下载安装redux-saga
yarn add redux-saga
  • 2.配置:创建store时进行中间件的配置
// res/store/index.js
import { createStore,applyMiddleware } from 'redux'
import reducer from './reducer'

// 引入redux-saga中间件
import createSagaMiddleware from 'redux-saga'
import mySaga from './mySaga'
// 创建saga中间件
const sagaMiddleware = createSagaMiddleware()

const store = createStore(
    reducer,
    applyMiddleware(sagaMiddleware)
)

// 监听mySaga文件
sagaMiddleware.run(mySaga)

export default store
  • 3.mySaga.js
// res/store/mySaga.js
// 这里看清楚:是redux-saga/effects
import { takeEvery, put } from 'redux-saga/effects'
import axios from 'axios'

function* getInitLists(){
    const res = yield axios.get('http://localhost:3000/api/lists')
    yield put({
        type: 'init_list_data',
        value: res.data
    })

}

function* mySaga() {
    yield takeEvery("init_data", getInitLists);
}

export default mySaga
// res/store/reducer.js
let defaultState = {
    inputValue: '',
    lists: []
}

export default (state=defaultState,action)=>{
    if(action.type==='change_input_value'){
        let newState = JSON.parse(JSON.stringify(state))
        newState.inputValue = action.value
        return newState
    }
    if(action.type==='init_list_data'){
        let newState = JSON.parse(JSON.stringify(state))
        newState.lists = action.value
        return newState
    }
    return state
}

// src/App.js
import React, { Component } from 'react';
import { Button, Input, List } from 'antd'
import 'antd/dist/antd.css'
import store from './store'

class App extends Component {
  constructor(props) {
    super(props);
    this.state = store.getState();
    this.handleUpdate = this.handleUpdate.bind(this)
    store.subscribe(this.handleUpdate)

    this.handleChange = this.handleChange.bind(this)
  }
  handleUpdate(){
    this.setState(store.getState())
  }
  handleChange(e){
    const action = {
      type: 'change_input_value',
      value: e.target.value
    }
    store.dispatch(action)
  }
  componentDidMount() {
    // 这里的dispatch会被mySaga.js中获取到
    const action = {
      type: 'init_data'
    }
    store.dispatch(action)
  }
  render() {
    return (
      <div style={{padding: '10px 0 0 10px'}}>
        <Input 
          style={{width: '300px',marginRight: '20px'}}
          placeholder='info'
          value={this.state.inputValue}
          onChange={this.handleChange}
        >
        </Input>
        <Button
        >添加</Button>
        <List
          style={{width: '380px',marginTop: '10px'}}
          bordered
          dataSource={this.state.lists}
          renderItem={item => (
            <List.Item>
              {item}
            </List.Item>
          )}
        />
      </div>
    );
  }
}

export default App;

相关文章

网友评论

      本文标题:redux-saga中间件的使用

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