react-redux里@connect
为什么可以直接拿到对象里的属性,而connect(mapStateToProps, mapDispatchToProps)(App)必须要手动才能拿到对象里的属性?比如:
const initialState = {
isAuth: false,
username: 'ok'
}
export function auth(state=initialState, action){
...
}
@connect(
state => state.auth
)
class App extends Component{
render(){
return(
{this.props.isAuth ? '<button></button>' : ''}
...
)
}
}
在这里使用装饰器的写法,可以直接拿到isAuth
.
但是改成mapStateToProps
要拿到isAuth
就必须换成这种写法:
const mapStateToProps = state => {
return{
isAuth: state.auth.isAuth
}
}
下面这种写法拿不到isAuth,
const mapStateToProps = state => {
return{
auth: state.auth
}
}
在组件中加上this.props.auth.isAuth才能对isAuth进行判断
问题是@connect
对auth这个对象做了什么,让我们不用写isAuth: state.auth.isAuth
就可以拿到isAuth?
@connect
接受一个函数作为参数,将这个函数的返回值对象展开传给组件,即作为组件的props