gpt4 book ai didi

javascript - 为什么 React Redux context.store 在子组件中未定义?

转载 作者:行者123 更新时间:2023-12-03 07:11:12 24 4
gpt4 key购买 nike

我试图从子组件访问存储,但它始终未定义,因此我必须将属性传递给子组件。

这是主要的应用程序起点:

ReactDOM.render(
<Provider store={store}>
<SignUpContainer />
</Provider>,
container
);

哪里 SignUpContainer是:
const SignUpContainer = connect(
mapStateToProps,
mapDispatchToProps
)(SignUpComponent);

哪里 SignUpComponent是一个正常的 react 组件:
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 .
定义上下文有什么问题吗?

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

react 版本是: 16.8.6 .

最佳答案

通常你会在通过 mapStateToProps 连接到 store 时将所需的 props 传递给组件然后您可以在组件中作为常规 Prop 进行访问。

所以例如

// 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);

关于javascript - 为什么 React Redux context.store 在子组件中未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59262539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com