- Redux
一、Redux 三大原则:
1、一个应用永远只有一个数据源(整个应用状态都保存在一个对象中,Redux提供的工具函数combineReducers可以解决庞大的数据对象的问题)
2、状态是只读的,不能直接修改,而是派发action
3、状态修改均由reducer 这样的纯函数完成
二、在项目中使用
1、在项目入口文件中import
--------若没有则需要安装,ts语法下安装使用 npm install @types/redux的方式
import { createStore, applyMiddleware } from "redux";
2、创建store
// App 是使用combineReducers方法生成的容器组件,里面融合了多个reducer
export const store = createStore(App, applyMiddleware(thunk));
createStore方法创建的是一个对象,它本身又包含4个方法
getState():获取store中的数据 及 状态
dispatch(action):分发一个action ,并返回整个action,这是唯一能改变store中数据的方式
subscribe(listener):注册一个监听者,它在store发生变化时被调用
- React-Redux
1、与redux一样在项目入口文件中import并使用
2、在项目中使用时与redux则不同,react-redux提供了 connect()方法:export default connect(mapStateToProps, mapDispatchToProps)(Form.create()(ScheduleList));
来获取store数据的功能
// 从store 中取数据,此时的this.props包含的有(父组件传过来的数据)和(在这个方法中获取到的数据)
const mapStateToProps = (state) => {
return ({
count: state.counter.count
})
}
// 派发action改变store数据,这里边不能调用这个外边的类中的其他方法,可以在其它方法中以this.props.func()的方法调用这里边派发action的方法, 注:ownProps为别的组件传过来的属性或方法
const mapDispatchToProps=(dispatch,ownProps)=>{
return{
handleInputFocus(){
dispatch(actionCreaters.getList());
dispatch(actionCreaters.searchFocus());
},
handleInputBlur(){
dispatch(actionCreaters.searchBlur());
},
handleMouseEnter(){
dispatch(actionCreaters.mouseEnter());
},
handleMouseLeave(){
dispatch(actionCreaters.mouseLeave());
},
handleChangePage(page,totalPage){
if(page < totalPage){
dispatch(actionCreaters.changePage(page + 1));
}else{
dispatch(actionCreaters.changePage(1));
}
}
}
}