安装 React Redux
Redux 默认并不包含 React 绑定库,需要单独安装。
npm install --save react-redux
容器组件和展示组件
| 展示组件 | 容器组件 |
作用 | 描述如何展现(骨架、样式) | 描述如何运行(数据获取、状态更新) |
直接使用 Redux | 否 | 是 |
数据来源 | props | 监听 Redux state |
数据修改 | 从 props 调用回调函数 | 向 Redux 派发 actions |
调用方式 | 手动 | 通常由 React Redux 生成 |
技术上讲你可以直接使用 store.subscribe() 来编写容器组件。但不建议这么做,而是使用 React Redux 的 connect() 方法来生成
容器组件和展示组件在职责上面有区别,代码上面无区别,如果不了解可以问百度
React Redux完整示例
动作类型
export const HelloActionType = 'HelloActionType'
创建动作函数
export function createHelloAction(isShow){
return { type : HelloActionType , isShow }
}
根据action创建Reducer
function helloReducer(state = true, action) {
switch (action.type) {
case HelloActionType:
return action.isShow;
default:
return state;
}
}
生成根Reducer
const todoApp = combineReducers({
showHello: helloReducer
})
使用根Reducer创建store
let store = createStore(todoApp)
创建应用程序入口文件index.js
import { Provider } from 'react-redux'
render(
<Provider store={store}>
<HelloContain />
</Provider>,
document.body
)
其中Provider作为应用的根,接收store,这样在子组件中便可访问store
创建Hello的容器组件HelloContain
const mapStateToProps = (state, ownProps) => { // ownProps为当前组件的props
return {
isShow: state.showHello
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
setShowHello: (isShow) => { dispatch(createHelloAction(isShow)) }
}
}
const HelloContain = connect(
mapStateToProps, // 关于state
mapDispatchToProps // 关于dispatch
)(Hello)
export default HelloContain;
这里使用connect来创建容器组件,connect第一个参数为state的委托,第二个参数为dispatch的委托,两个个委托均返回展示组件Hello的props,connect 位于 react-redux 中 import { connect } from 'react-redux'
创建hello展示组件
export default class Hello extends React.Component {
render() {
return (<div>
<h1>{this.props.isShow && "Hello"}</h1>
<button onClick={() => this.props.setShowHello(!this.props.isShow)}>
{this.props.isShow ? "隐藏" : "显示"}
</button>
</div>)
}
}
上述应用数据流为:
- let store = createStore(todoApp)创建store,store生成初始化state
- <Provider store={store}>将store放入上下文中,每个组件都可以访问
- 使用connect创建容器组件HelloContain,connect调用store.subscribe(listener)为HelloContain安装监听器
- 容器组件HelloContain监听store获取state,调用其mapStateToProps 和mapDispatchToProps 委托,生成展示组件Hello的props
- 展示组件利用props展示数据,展示组件点击隐藏按钮,触发props的setShowHello委托,setShowHello由HelloContain定义
- HelloContain的setShowHello触发dispatch,传入一个动作
- helloReducer处理的这个动作,并返回新的state个store
- 所有监听器被触发,返回步骤4