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