I try to use a prop value to set a state but it keeps giving me null. The prop value has a valid
value (boolean).
This is the constructor of the child component:
constructor(props: any) {
super(props);
this.setState({
...this.state,
customUser: props.customUser,
open: props.open
})
}
If I log the prop it will give the value true, as I want. But when this value is used to set the state in the constructor. It will return null here and not render:
render() {
return (
here ---> <Dialog open={this.state.open}>
<DialogTitle>Account Delete</DialogTitle>
<DialogContent>
<p>Are you sure you want to delete your account?</p>
</DialogContent>
<DialogActions>
<Button variant="contained" color="primary" onClick={() => {
}}>Yes</Button>
<Button variant="contained" color="secondary" onClick={() => {this.toggleDialog}}>No</Button>
</DialogActions>
</Dialog>
)
}
I tried using a different named state to set the prop value to. But this didn’t work either.
2
Answers
As the response of Andy Ray said, I used setState instead of this.state. Replacing this fixed my issue. Thanks!
Try to do it with
componentDitMount
(oruseEffect
with newer version).You can do it like this with
componentDidMount
.