首页 > 解决方案 > 我可以在组件中使用 redux 来避免道具钻孔吗?

问题描述

假设我有这个结构

 _______________
| HomeContainer |
 ---------------
        |         _______________   
        |-------- | ComponentX |
                   --------------
                        |       _____________
                        |------ | ComponentZ |
                                --------------   _____________
                                      |---------|  User      |
                                                 -------------

以及以下用户代码

const User = (props) => {
  return <h1>{props.user.name}</h1>
}

const mapStateToProps = state => {
  return {
    user: state.auth.user // I have an auth reducer mapped in the store
  }
}

export default connect(mapStateToProps)(User)

Redux是否可以避免将用户传递给即使只是一个组件而不是容器ComponentXComponentZUser

Redux为支柱钻井提供什么解决方案?

标签: javascriptreactjsredux

解决方案


当然,您只需要使用 react-redux 中的 connect 函数,它接受两个参数,第一个是状态,第二个是调度动作,如下面的代码。

import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { MyAuthActions } from '../some/actions/files' //<--- my action file

const User = ({ user }) => <h1 onClick={myActionFunction}>{user.name}</h1> //<---- myActionFunction was created in my action created file dispatch

const state = ({ auth }) => ({ user: auth.user })
const dispatch = dispatch => bindActionCreators(MyAuthActions, dispatch)

export default connect(state, dispatch)(User)

推荐阅读