【发布时间】:2022-08-08 23:22:36
【问题描述】:
这是来自 redux store 的响应:
{
\"newsletter\": true,
\"orderConfirmation\": true,
\"shippingInformation\": true,
\"orderEnquiryConfirmation\": true,
}
这是 jsx 文件,我试图在其中设置状态。这个想法是从响应中设置状态并为每个复选框添加一个 onChange 句柄。
但目前正在收到正确的响应,但我尝试在 didUpdate、DidMount 中设置状态但没有运气。我想知道在组件初始渲染时设置状态的正确位置。
import React from \'react\';
import Component from \'../../assets/js/app/component.jsx\';
import { connect } from \'react-redux\';
import * as actionCreators from \'../../assets/js/app/some/actions\';
import { bindActionCreators } from \'redux\';
import Checkbox from \'../checkbox/checkbox.jsx\';
const mapStateToProps = (state, ownProps) => {
return {
...state.emailSubscriptions
}
}
const mapDispatchToProps = dispatch => {
return {
actions: bindActionCreators(actionCreators, dispatch)
}
}
@connect(mapStateToProps, mapDispatchToProps)
class EmailSubscriptions extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
this.props.actions.getEmailSubscriptions();
this.setState({ // Not setting state
notifications: [
newsletter = this.props.newsletter,
orderConfirmation = this.props.orderConfirmation,
shippingInformation = this.props.shippingInformation,
orderEnquiryConfirmation = this.props.orderEnquiryConfirmation
]
})
}
render() {
return (
<div>
Here I want to use loop through state to create checkboxes
{this.state.notifications&& this.state.notifications.map((item, index) => {
const checkboxProps = {
id: \'subscription\' + index,
name: \'subscription\',
checked: item.subscription ? true : false,
onChange: (e)=>{ return this.onChange(e, index)},
};
return <div key={index}>
<Checkbox {...checkboxProps} />
</div>
</div>
)
}
}
export default EmailSubscriptions;
标签: reactjs react-redux react-state react-state-management react-lifecycle