redux笔记 进阶

1 拆分UI组件和容器组件

 

import React from 'react'
const AppUI = (props) =>{
  return (
    <div className="App">
      <label htmlFor="box">
        输入信息
        <input id="box" 
          value = {props.inputValue} 
          onChange = {props.handleInputChange}
        />
        <button onClick={props.submitData}>提交</button>
        </label>
      <ul>
       {
         props.list.map((item,index) => {
            return (
              <li key={index} onClick={props.deleteList.bind(this,index) }>{item}</li>
            )
         })
       }
      </ul>
    </div>
  );
}
export default AppUI;

对应的聪明组件:

render() {
    const {inputValue,list} = this.state
    return (
      <AppUI
      inputValue = {inputValue}
      handleInputChange = {this.handleInputChange}
      submitData = {this.submitData}
      list = {list}
      deleteList = {this.deleteList}
      />
    );
 }

 2 异步请求可以放在组件中,如下所示:

componentDidMount(){
    axios.get('/userList.json').then((res)=>{
      store.dispatch(initListData(res.data))
    })
  }

但是不便于统一管理,使用redux-thunk 中间件,将其放在creact actionor中,首先安装redux-thunk:

在store中定义:

import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, composeEnhancers(
    applyMiddleware(thunk)
));

export default store;

如上所示:既可以使用插件也可以使用thunk;

不使用redux-thunk时,action只能是一个对象,有了redux-thunk之后,action就可以是一个函数了。

  • 安装:npm install redux-thunk --save

其中store/index.js文件

import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, composeEnhancers(
    applyMiddleware(thunk)
));

export default store;

对应的actionCreator.js

import {CHANGE_INPUT_VSLUE,INITDATA}  from '@/store/actionType.js'
import * as API from '@/api';
import store from './index.js';
import axios from "axios";

export const changeInputValue = (value)=>({
    type:CHANGE_INPUT_VSLUE,
    value
})

export const getListData = ()=>{
    return async()=>{   // 注意这里要return出去 另外注意箭头函数 =>({xxx}),表示直接把对象renturn出去了
        let response = await API.getData();
        store.dispatch({
            type:INITDATA,
            initData:response.rs
        })
    }
}

 

posted @ 2019-03-16 22:34  小猪冒泡  阅读(121)  评论(0编辑  收藏  举报