我有一个父组件“ ParentPage”,它将通过道具将选定的程序值传递给它的子组件。 从子组件中选择单选按钮时,将调用“ handleProgramOption”,并更新状态。 state.program作为prop传递给子组件。
我的问题是在初始加载时,当mapStateToProps返回新的prop值时如何更新状态,以便在渲染时子组件获得新的值。
父组件
class ParentPage extends React.Component {
constructor(props) {
super(props);
this.state = {
program: undefined
};
this.handleProgramOption = this.handleProgramOption.bind(this);
this.handleNext = this.handleNext.bind(this);
this.handlePrev = this.handlePrev.bind(this);
}
componentDidMount() {
this.props.getProgram()
}
handleProgramOption = (e) => {
const value = e.target.value;
this.setState({program: value});
};
handleNext() {
this.props.addProgram({program: this.props.program});
}
handlePrev() {
this.props.history.push('/');
}
render() {
return (
<ChildSection
selectedProgram={this.state.program}
handleProgramOption={this.handleProgramOption}
/>
);
}
}
const mapStateToProps = state => {
return {
program: state.program
}
}
export default connect(mapStateToProps, {addProgram, getProgram})(ParentPage);
子组件
const ChildSection = ({selectedProgram, handleProgramOption}) => {
return (
<FormControl>
<RadioGroup
aria-label="program"
name="program"
value={selectedProgram}
onChange={handleProgramOption}
>
<FormControlLabel
value="A"
control={<Radio color="primary"/>}
label="A"
labelPlacement="start"
/>
<FormControlLabel
value="B"
control={<Radio color="primary"/>}
label="B"
labelPlacement="start"
/>
</RadioGroup>
</FormControl>
)
};
export default ChildSection