首页 > IT职业 > IT图书 > 20180911 redux 粗浅使用
redux是一个状态管理器
用于生成各种state, state就是redux的数据载体,可以是数组,也可以是对象
// store由createStore生成 const store = createStore(store);
// dispatch需要派发属性为type的对象,这个对象一般都在action中存着
store.dispatch({ type:'aciton'
});
// 订阅store的变化 let sub = store.subscribe(listener); // subscribe 返回的函数用来注销相应的监听器 sub();
// getState 是一个方法,获取当前的状态
store.getState(); // 结合上一个api进行使用
store.subscribe(() => {
store.getState(); // 监听并获取当前的状态
})
const ComponentTest = (props) =>const NewComponent = connect( mapStateToProps, mapDispatchToProps )(ComponentTest)
mapStateToProps 这里需要返回一个对象
const mapStateToProps = (state, ownerProps) => { // ownerProps 是 NewComponent 上传入的属性
// reducer上的state
// 此处的state不是react的state
// 这块就是将redux的state映射到组件ComponentTest的props上的过程
return { value: state.value
}
}
mapDispatchToProps 这里也需要返回一个对象
const mapDispatchToProps = (dispatch, ownerProps) => { // ComponentTest 上的事件event 派发某个action
// 这块是将redux的派发事件映射到组件ComponentTest 的props上,组件的事件激发了派发事件
return { event:() => dispatch({type:'action'})
}
}
connect()(Component)
// 当connect中不传任何参数的时候:// Component 这个组件上props传入dispatch,也就是说class ComponentTest extends Component{
render(){ // 这个组件的props上会有有个dispatch的方法
const dispatch = this.props.dispatch
}
}

redux.png
作者:Aaron_Alphabet
链接:https://www.jianshu.com/p/55bbcacaf43e
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2041/viewspace-2814422/ ,如需转载,请注明出处,否则将追究法律责任。