Notes:
1.Never use “this.setState” in constructor because it is only used after the component has been mounted.
2. Always return something from getDerivedStateFromProps
function and we cannot use ‘this’ in getDerivedStateFromProps function. So all the this.XXX functionality has to be done in render() or constructor() functions. As I have called functions in constructor and returned null in case no condition is matched in getDerivedStateFromProps function.
3. If you have not used typescript then please search about that because it is used in the following example. (But there is no effect :-))
class AddBook extends Component<any, any>{
constructor(props: any) {
super(props);
this.state = {
id: "",
title: "",
selectedCategories: [],
categories: [],
authors: [],
topAuthors: [],
content: "",
edit: null,
categoryModalIsOpen: false,
authorModalIsOpen: false,
newcategory: null,
newauthor: null,
}
this.getCategories();
this.getTenAuthors();
if (this.props.location && this.props.location.state && this.props.location.state.id)
this.fetchContent(this.props.location.state.id);
if (!this.state.formSubmitFunction || this.state.formSubmitFunction != this.editBook)
this.state = { formSubmitFunction: this.addBook }
else
this.state = { formSubmitFunction: this.editBook }
}
static getDerivedStateFromProps(nextProps: any, currentState: any) {
if (nextProps.location &&
nextProps.location.state) {
if (nextProps.location.state.edit === false) {
return {
edit: false,
id: "",
title: "",
content: "",
selectedCategories: [],
categories: [],
authors: [],
}
}
else {
return {
id: nextProps.location.state.id,
selectedCategories: nextProps.location.state.selectedCategories,
title: nextProps.location.state.title,
edit: nextProps.location.state.edit,
authors: nextProps.location.state.authors
}
}
}
return null;
}
render() {
return null
}
}