首页 > 解决方案 > 为什么 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.storeundefined。定义上下文有什么问题吗?

我希望在不显式传递它们的情况下在子组件(以及子级别中的子组件)中隐式访问商店详细信息。

反应版本是:16.8.6.

标签: javascriptreactjsreduxreact-redux

解决方案


通常,当您连接到商店时,您会将所需的道具传递给组件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);

推荐阅读