Reputation: 3324
I have tried and failed to understand react/redux and have inherited some code (very simplified version shared here). There is a navigator:
class processNavigator extends React.Component<Props, State> {
render() {
switch (this.props.processStatus) {
case processStatus.ended:
return <Page2 />;
case processStatus.notStarted:
return <Page1 myToken={this.myToken} />;
which renders either page1 or page2.
Page1:
interface StateProps {
processId: number | undefined;
processStatus: processStatus | undefined;
}
interface DispatchProps {
startprocess: () => void;
}
type Page1Props = RouteComponentProps &
DispatchProps &
NavigatorProps &
StateProps;
class Page1 extends React.Component<Page1Props, {state variables
}> {
constructor(props: any) {
super(props);
this.state = { state variables
};
}
startTypeGetPromise = async (myToken: string): Promise<any> => {
DB lookup here
return aValue;
};
loadResult = async () => {
await this.startTypeGetPromise(this.props.myToken).then(ret => this.setState({startTypeValue: ret}));
};
componentDidMount () {this.loadResult();};
render() {return (...);}
}
const mapStateToProps = (state: RootState): StateProps => ({
processId: state.process.processId,
processStatus: state.process.processStatus,
});
const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => ({
startprocess: () => dispatch(startprocess()),
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(withRouter(withTranslation()(Page1)));
Page2:
interface StateProps {
processId: number | undefined;
processStatus: processStatus;
}
type Page2Props = RouteComponentProps & StateProps;
class Page2 extends React.Component<Page2Props> {
render() {...);}
}
const mapStateToProps = (state: RootState): StateProps => ({
processId: state.process.processId,
processStatus: state.process.processStatus,
});
export default connect(mapStateToProps)(
withRouter(withTranslation()(processPage2))
);
How do I pass the state value startTypeValue
from Page1
to Page2
? (Apologies for all the code, I am not sure what is boiler plate and what is needed).
Upvotes: 0
Views: 59
Reputation: 914
You can move startTypeValue to the upper component's state and pass it as a prop to Page2. For changing startTypeValue from Page1 component one can pass a callback function-prop:
class processNavigator extends React.Component<Props, State> {
state = {
startTypeValue: null // or some other initial value you want
}
render() {
switch (this.props.processStatus) {
case processStatus.ended:
return <Page2 startTypeValue={this.state.startTypeValue} />;
case processStatus.notStarted:
return <Page1
myToken={this.myToken}
onValueChange={(value) => this.setState({ startTypeValue: value })}
/>;
}
}
In Page1 component:
loadResult = async () => {
await this.startTypeGetPromise(this.props.myToken)
.then(ret => this.props.onValueChange(ret));
};
Upvotes: 1