在 redux 当中,用下面两种方式都可以获取到 store 中的状态:
- 引入 store 文件,然后直接在组件里面调用
store.getState()方法 - 引入 connect 方法,然后用
mapStateToProps把状态映射到组件的 props 上面
下面是两种方式都使用的案例:
import React, { Component } from 'react'
import store from '../store'
import { connect } from 'react-redux'
class Test extends Component {
constructor(props) {
super(props);
}
render() {
return (
<p>
<h1>{this.props.count}</h1>
<h2>{store.getState().reducer1.count}</h2>
</p>
)
}
}
const mapStateToProps = (state) => ({
count: state.reducer1.count
})
export default connect(mapStateToProps)(Test)
既然这两种方式都可以获取状态,那到底用哪种好呢?从功能实现角度其实是无所谓的,从代码工程化、可复用的角度,mapStateToProps 会更优一点,举个例子:
假如你为了完成某个项目的具体需求,写了一个组件,里面直接使用 store.getState() 来获取 username 状态,但是 store 存储的变量是当前项目的所有状态,如果在另外一个项目中,store 是完全不一样的,但是如果用
mapStateToProps方法把 username 放到 props 里面,这个组件就可以不用 care 它的来源,然后直接 copy 到另外一个项目中直接使用啦!
总结起来就是:如果你如果想在其他项目中复用这个组件的话,建议使用 mapStateToProps 。最后放一张经典的图,形象地表示了状态是如何从 store 流入组件的 props 中的: