React-Redux 高级

UI组件和容器组件的拆分
  • ui组件负责渲染
无状态组件

一个组件只有一个render()函数,性能较高,由一个类变成了一个函数,多用于无状态组件
可以写成

const name=(props)=>{
	return(
		)
	}
	export default name
	//此时this.props.xxxx ⇒ props.xxx
Redux 异步获取数据
import axios from 'axios';
axios.get('static/api/list.json').then((res)=>{
      const action=setList(res.data.data)
      store.dispatch(action)
    })
使用Redux-thunk 中间件进行异步请求

为了避免组件过于臃肿,可以把异步请求单独拆分出去
redux-thunk 可以让我们把其拆分到action里面去
github:redux-thunk

npm install redux-thunk

//  以下是引入Readux-thunk
// 在创建store 时引用

import { createStore,applyMiddleware,compose  } from 'redux';
import reducer from './reducer'
import thunk from 'redux-thunk';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?   
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const enhancer = composeEnhancers(
  applyMiddleware(thunk),

);
const store = createStore(reducer, enhancer);
export default store;
// redux-thunk 让action可以是一个函数


Redux 中间件

中间指的是action 和store 之间
对dispatch 进行升级,让dispatch根据参数的不同执行不同的操作,如果参数是对象,直接给store,如果参数是函数,执行之后在给store

在这里插入图片描述

Redux-saga 中间件进行异步处理
import {  put,takeEvery} from 'redux-saga/effects'
import { saga_get  } from './actionTypes'
import { setList } from './actionCreators'
import axios from 'axios'
function* getInitList(){
  const res=yield axios.get('./static/api/list.json')
  const action=setList(res.data.data);
  yield put(action);
}

function* sagas() {
  yield takeEvery(saga_get, getInitList);
}

export default sagas
React-Redux的使用

import React,{Component } from ‘react’
import store from ‘./store’
class Todolist extends Component{
render(){

return(
  <div>
    <div>
      <input />
      <button>提交</button>
    </div>
    <ul>
      <li>xxx</li>
    </ul>
  </div>
)

}
}

export default Todolist

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值