简体   繁体   中英

React component state becomes invalid after change in parent component

function UserCard({ user }) {
  let defaultUserName = user.nicknames[0];
  let [selectedNickname, setSelectedNickname] = React.useState(defaultUserName);

  // The selected nickname becomes invalid when the user is changed!!!
  const selectedNicknameIsValid = user.nicknames.includes(selectedNickname);

  return (<div>
     <UserCardWithNickName user={user} selectedNickname={selectedNickname} />
     <SelectNickName user={user} setSelectedNickname={setSelectedNickname} />
  </div>);

In the above snippet the component's state holds the selected nickname from the list of user nicknames. But when the user changes in the parent component this component is re-rendered with the same state. So the nickname in the state is for the wrong user.

What is the preferred way to handle this? A lot of google searching couldn't find much discussion.

Am I doing this in some fundamental non-react way?

Is the preferred solution to use useEffect to fix the state when it becomes invalid as discussed here React.useState does not reload state from props ?

Working example oncodesandbox

Yeah, state changes in the parent component will usually re-render the child component, and hence reset the state of the child component. I'd suggest moving states that you want preserved up into the parent tree.

State management is an important concept in React. As your app grows, you'll realize doing this will add a lot of bloat and repetitive code. Learning about state management will prove very useful for you!

Yes. The link you have posted is one way to do it. The question you have to look for is if your child component is managing the value of selectedNickname in anyway. That is the only reason you would want to keep it as a seperate state in the child component. If all it does is read the props from the parent, simply use the props and do not maintain an internal state at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM