In this post, we will see how to resolve What am i doing wrong here where state doesn’t seem to update on child BasePagination?
Question:
The problem I’m having is that the initial state is never updated on BasePagination even though it’s clearly being re-rendered and the parent component is successfully changing the page and setting the new state.. But it’s not getting through to the child component even though it’s explicitly setting in JSX attributes in render method.Parent component:
Best Answer:
You are copying props into state, which is a common antipattern. It’s generally a bad idea to get the props and put them into local component state as you now have 2 copies lying around that can get out of sync unless you write a lot of unnecessary glue code to sync them. Why not just use theprops
directly?This is the reason why the parent updates don’t effect the child. You initialize the child with the parent state, and then future state updates in the parent are irrelevant to the child since there’s no code to copy updates. But as above, the copy itself is not necessary and an unnecessary barrier.
In
BasePagination
, just use the props directly:pages
outside your component definition as when these change, you won’t get a rerender. You can’t use module scope as state. I have removed this. It’s not needed anyway.maxPages
is ok since it is just a constant and not mutated.If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com
Leave a Review