简体   繁体   English

React 组件状态在父组件更改后变得无效

[英]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 ?使用 useEffect 在状态变为无效时修复状态的首选解决方案是否如此处所述React.useState 不会从道具重新加载状态

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.状态管理是 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.您必须寻找的问题是您的子组件是否无论如何都在管理 selectedNickname 的值。 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.如果它所做的只是从父级读取道具,则只需使用道具并且根本不维护内部状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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