1.为什么要使用react-redux?
回答这个问题,只需要明确我们的最终目的:能在react组件中实现对store中的state进行获取、修改、监听,而从上述内容可以知道,createStore会给我们返回getState、dispatch、subscribe来进行获取state、修改state、监听state变化,而我们现在要做的就是把这个三个函数传递给react组件就可以了,所以我们就需要react-redux来帮助我们。
2.react-redux的核心原理是什么?
1.将Provider高阶组件包裹在组件的最外层,并且将创建的store传入Provider高阶组件中,
然后再Provider高阶组件内部获取传入的store并将它添加到Provider高阶组件的context上下文中,context是react组件特有的一种不用手动一层层传递props就能在组件树中传递数据的方式,这样就实现了store相对于react组件的全局化,所有组件都能对store进行修改,获取。
2.虽然Provider下的组件都拥有可以操作store的能力了,但是由于倘若我们要在每一个组件都从context中去获取store会造成大量代码冗余,还有一点就是即使你能在react组件中能够操作store了,但是当你dispatch一个action之后,store中的state虽然更新了,但是并不会触发组件中的render函数去渲染新的数据,所以我们就需要通过react-redux另一个高阶组件connect
来做集中处理。connect组件接受一个component组件返回一个新的component组件,在connect最终返回的组件中获取store并将store设置为当前组件的state,并且在connect返回的组件中的componentDidMount周期函数中调用subscribe给store绑定监听函数,而这个监听函数就是负责当前store中的state发生改变时,通过this.setState来触发组件的render函数的调用,最终达到store中的state与UI中s
3.react-redux有哪些API?
1.Provider组件通过context的方式将store注入应用
2.Connect高阶组件,获取并监听store,然后根据store state和组件自身props计算得到新props,注入该组件,并且可以通过监听store,比较计算出的新props判断是否需要更新组件
tate同步的问题
Provider的实现
import React, { Component } from 'react'
import PropTypes from 'prop-types'
class Provider extends Component {
constructor (props) {
super(props)
this.store = props.store
}
static propTypes = {
store: PropTypes.object
}
getChildContext () {
return { store: this.store }
}
render () {
return this.props.children
}
}复制代码
connect的实现
import React, { Component } from 'react'
import PropTyeps from 'prop-types'
import { bindActionCreator } from 'redux'
const connect = (mapStateToProps, dispatchStateToProps) => (WrapperComponent) => class Connect extends Component {
construtor (props, context) {
super(props, context)
this.store = context.store
this.state = {
props: {}
}
}
static contextTypes = {
store: PropTypes.object
}
componentDidMount () {
this.store.subscribe(this.update)
this.update()
}
update = () => {
const { getState, dispatch } = this.store
const stateProps = mapStateToProps(getState())
const dispatchProps = bindActionCreator(dispatchStateToProps, dispatch)
this.setState({
...this.state.props,
...stateProps,
...dispatchProps,
})
}
render () {
const { props } = this.state
return <WrapperComponent {...props} />
}
}复制代码