javascript - 我可以在组件中使用 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
是否可以避免将用户传递给即使只是一个组件而不是容器ComponentX
?ComponentZ
User
Redux
为支柱钻井提供什么解决方案?
解决方案
当然,您只需要使用 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)
推荐阅读
- unity3d - 区分具有相同标签的游戏对象碰撞器
- javascript - 带有 Internet Explorer 的 Babel
- python - 如何使用 python 返回 JSON 中的上部字段?
- java - 为什么会发生此异常'o.StreamCorruptedException:无效的流标头:D8322EDA'
- typescript - 从 MockedFunction 到 Mock
- server-side-rendering - 如何避免在 Sapper 应用中多次预加载相同的数据?
- elasticsearch - 根映射定义在运行弹性搜索无痛脚本时具有不受支持的参数(mapper_parsing_exception)
- c++ - 使用静态分配的派生类对象初始化基类指针数组
- css - 在 Angular 中,是否可以有多个 CSS 选择器?
- javascript - 有角度 [ngClass] 动态刷新类(基于服务中更新的数据)