I'm confused about the refactoring of my code.
My Component works like this ==> I set the incoming props from the parent component to the child component's state. Then I can do the update state operations in the component.
This is my UNSAFE_componentWillReceiveProps
function:
UNSAFE_componentWillReceiveProps = (nextProps) => {
if (nextProps
&& nextProps.actionToEdit
&& nextProps.actionToEdit.statement
) {
const regex = /@\w+/g;
const found = nextProps.actionToEdit.statement.match(regex);
this.setState({
parameters: found
});
}
};
This is my getDerivedStateFromProps
function:
static getDerivedStateFromProps(
nextProps: ICustomActionModalProps,
prevState: ICustomActionModalState
) {
if (nextProps
&& nextProps.actionToEdit
&& nextProps.actionToEdit.statement
) {
const regex = /@\w+/g;
const found = nextProps.actionToEdit.statement.match(regex);
return {
parameters: found
};
}
return null;
}
This is my onChange function:
onChange = (newValue, e) => {
const regex = /@\w+/g;
const found = newValue.match(regex);
this.setState({ parameters: found });
};
I realized something when onChange worked.
==> If I use UNSAFE_componentWillReceiveProps
, the state updated perfectly. Because when the onChange function works every time UNSAFE_componentWillReceiveProps
doesn't work.
However,
==> If I use getDerivedStateFromProps
, the state updated with old props. Because when the onChange function works every time getDerivedStateFromProps
works too.
I just want my getDerivedStateFromProps
function will able to works like my old UNSAFE_componentWillReceiveProps
function.
How can I do that? Thanks