首页 > IT职业 > IT图书 > React-Redux API 学习小记
UI 组件特征:
UI 组件示例:
const Title = value => {value}
; 容器组件(逻辑组件) 容器组件特征:
如果一个组件既有 UI 呈现又有业务逻辑,则将它封装为如下结构:
由 UI 组件生成容器组件,需要三个要素:
容器组件的三要素对应 React-Redux 的 API:
其中,mapStateToProps 和 mapDispatchToProps 作为 connect 的参数传入
import {connect} from 'react-redux';
const Container = connect(
mapStateToProps,
mapDispatchToProps
)(Component); const mapStateToProps = (state, ownProps) => {
return props;
}; mapStateToProps 会订阅 Store,每当 state 更新,就会自动执行,重新计算 UI 组件的 props,从而触发 UI 组件的重新渲染
3.1 mapDispatchToProps 函数:
const mapDispatchToProps = (dispatch, ownProps) => {
return {
handleClick: () => {
dispatch(action);
}
};
}; 3.2 mapDispatchToProps 对象:
const mapDispatchToProps = {
handleClick: actionCreator;
}; mapDispatchToProps 用来建立 UI 组件的 props 到 Store.dispatch 方法的映射
至此,容器组件与内部的 UI 组件的通信已经解决。容器组件还需要与外部通信,拿到 state 对象。
React-Redux 提供 Provider 组件,可以让容器组件拿到 state。
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import todoApp from './reducers';
import App from './components/App';
const store = createStore(todoApp);
render(
,
document.getElementById('root')
); React-Redux 综合实例:Provider 在【根组件】App 外面包了一层。这样,所有子组件就可以拿到 state 了
流程概括如下:
Component
- [mapDispatchToProps/mapDispatchToProps] -
=> Container
- [connect] -
- [Reducer] -
=> Store + Provider 导入所需组件(确保依赖已安装)
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import {createStore} from 'redux';
import {Provider, connect} from 'react-redux'; 定义 UI 组件
class Counter extends Component {
render() {
const {value, onIncreaseClick} = this.props
return (
{value}
);
}
}
Counter.propTypes = {
value: PropTypes.number.isRequired,
onIncreaseClick: PropTypes.func.isRequired
}; 定义组件通信
// Action Creator
const increaseAction = {
type: 'increase'
};
const mapStateToProps = state => {
return {value: state.count}
};
const mapDispatchToProps = dispatch => {
return {
onIncreaseClick: () => dispatch(increaseAction);
}
}; 包装容器组件
const App = connect(
mapStateToProps,
mapDispatchToProps
)(Counter); 定义 Reducer
function counter(state = {count: 0}, action) {
const count = state.count;
switch (action.type) {
case 'increase':
return {
count: count + 1
};
default:
return state;
}
} 生成 Store 对象
const store = createStore(counter)
ReactDOM.render(
,
document.getElementById('root')
); Tips: 本文总结自阮一峰老师的文章 React-Redux 的用法,如果对您有帮助,可以给阮一峰老师留言感谢 !
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2866/viewspace-2807992/ ,如需转载,请注明出处,否则将追究法律责任。