javascript - 为什么 React Redux context.store 在子组件中未定义?
问题描述
我正在尝试从子组件访问存储,但它始终未定义,因此我必须将属性传递给子组件。
这是主要的应用程序起点:
ReactDOM.render(
<Provider store={store}>
<SignUpContainer />
</Provider>,
container
);
在哪里SignUpContainer
:
const SignUpContainer = connect(
mapStateToProps,
mapDispatchToProps
)(SignUpComponent);
SignUpComponent
正常的反应组件在哪里:
export default class SignUpComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className={"sign-up-component " + this.context.store.theme}>
// Form
</div>
)
}
}
我总是越来越context.store
像undefined
。定义上下文有什么问题吗?
我希望在不显式传递它们的情况下在子组件(以及子级别中的子组件)中隐式访问商店详细信息。
反应版本是:16.8.6
.
解决方案
通常,当您连接到商店时,您会将所需的道具传递给组件mapStateToProps
,然后您可以在组件中作为常规道具访问。
所以例如
// State of type StoreType
const mapStateToProps = (state: StoreType) => ({
theme: state.theme
});
class Button extends React.Component {
render() {
return (
<button className={"button " + this.props.theme}>
Button
</button>
)
}
}
export default connect(
mapStateToProps
)(Button);
推荐阅读
- angularjs - Angularjs 错误:regeneratorRuntime 未使用异步函数定义
- javascript - Zapier 到 Twilio 生成动态短信正文
- ruby - 如何根据其转换对数组进行排序
- javascript - 在 React Native 中将 props 传递给 HTML 内容
- python-3.x - 如何接管包括空格在内的变量名
- swift - 调整 CollectionView 的单元格大小
- javascript - 如何用scroll-snap实现垂直滚动?
- jquery - 无法使用jquery获取多行表中的输入值
- xpath - 如何获取节点的所有直接父节点的列表?
- python - 模拟 Python 2 `file` 对象的 `fileno` 方法