React-redux
connect功能:连接容器组件和展示组件
使用 React Redux 库的 connect() 方法来生成容器组件前。容器组件就是使用 store.subscribe() 从 Redux state 树中读取部分数据,并通过 props 来把这些数据提供给要渲染的组件。你可以手工来开发容器组件,但建议使用 React Redux 库的 connect 方法来生成,这个方法做了性能优化来避免很多不必要的重复渲染。(这样你就不必为了性能而手动实现 React 性能优化建议 中的 shouldComponentUpdate
方法。)
import {connect} from 'react-redux';
export default connect {mapStateToProps, mapDispatchToProps}(className)
使用 connect() 前,需要先定义 mapStateToProps 这个函数来指定如何把当前 Redux store state 映射到展示组件的 props 中。
function mapStateToProps(state, ownProps) {
return {
value: state[ownProps.caption];
}
}
除了读取 state,容器组件还能分发 action。可以定义mapDispatchToProps() 方法接收 dispatch() 方法并返回期望注入到展示组件的 props 中的回调方法。它可以是一个函数,也可以是一个对象。如果mapDispatchToProps是一个函数,会得到dispatch和ownProps(容器组件的props对象)两个参数。
。
function mapDispatchToProps(dispatch, ownProps) {
return {
onIncrement: () => {
dispatch(Actions.increment(ownProps.caption));
}
}
}
//简化 以action 构造函数为对应字段值,把这样的对象直接传给
//bindActionCreators 函数,利用它将 action 构造函数和 props关联起来
import {bindActionCreators} from 'redux'
import {increment} from './actions'
const mapDispatchToProps = (dispatch) => bindActionCreators({
onIncrement: increment
}, dispatch)
//直接让 mapDispatchToProps 是一个 props 到action 构造函数的映射
const mapDispatchToProps = {
onIncrement: increment
}
最后,使用 connect() ,并传入这两个函数。
redux中的 combineReducres 函数
redux 中的 combineReducres 函数接受一个对象作为参数,参数对象的每个字段名对应了 State 状态上的字段名,每个字段值都是一个 reducer 函数,combineReducres返回一个新的 reducer 函数,当这个新的函数被执行时,会把传入的 state 参数对象拆开处理,把对应字段名的state交给对应值的 reducer 函数,在把调用的返回结果合并成一个新的 state,作为整体 reducer 函数的返回结果。
import {createStore, combineReducers} from 'redux';
import {reducer as todoReducer} from './todos';
// import {reducer as filterReducer} from './filter';
const reducer = combineReducers({
todos: todoReducer
});
export default createStore(reducer)
ref
当一个包含 ref 属性的组件完成装载过程的时候,会查看 ref 属性是不是一个函数,如果是就会调用这个函数,参数就是这个组件代表的 DOM (不是虚拟 DOM)元素。
<input className="new-todo" ref={this.refInput}/>
refInput(node) {
this.input = node;
console.log(node);
}