【问题标题】:State is not updating with correct information状态没有更新正确的信息
【发布时间】:2019-10-12 08:04:34
【问题描述】:

您好,我正在尝试更新我在 React 中的状态值,但我不知道为什么它总是转到未定义 selectedUser 的选项。我尝试将所有内容都放在 if-else 中,但得到了相同的结果,奇怪的是,当我在控制台中编写某些内容时,它进入了我的条件,但它取而代之的是空值。

const [inputFieldState, setInputFieldState] = useState(InputFields(selectedUser));

function InputFields(selectedUser: any) {

  return selectedUser
    ? selectedUser
    : {
        email: "",
        firstName: "",
        lastName: "",
        customerId: "",
        id: "",
        role: ""
      };
}

selectedUser 现在是一个假值

return {
    firstName: planes[Math.floor(Math.random() * planes.length)],
    lastName: planes[Math.floor(Math.random() * planes.length)],
    customerId: planes[Math.floor(Math.random() * planes.length)],
    id: planes[Math.floor(Math.random() * planes.length)],
    role: names[Math.floor(Math.random() * names.length)],
    email: Math.ceil(Math.random() * 5)
  };

当我对所选用户进行控制台日志时,我得到了

{firstName: "x-wing", lastName: "Winnebago", customerId: "y-wing", id: "TIE-fighter", role: "Anakin", …}
customerId: "y-wing"
email: 2
firstName: "x-wing"
id: "TIE-fighter"
lastName: "Winnebago"
role: "Anakin"

【问题讨论】:

  • 你从哪里获得 selectedUser 的价值?
  • selectedUser 是我创建的假值
  • return { firstName: planes[Math.floor(Math.random() * planes.length)], lastName: planes[Math.floor(Math.random() * planes.length)], customerId:planes[Math.floor(Math.random() * planes.length)],id:planes[Math.floor(Math.random() * planes.length)],角色:names[Math.floor(Math. random() * names.length)],电子邮件:Math.ceil(Math.random() * 5) };
  • 为什么selectedUser会有回报?

标签: reactjs typescript


【解决方案1】:

从 cmets 来看,selectedUser 是一个函数

const [inputFieldState, setInputFieldState] = useState(InputFields(selectedUser()));

function InputFields(user: any) { // just changed the name to avoid potential confusion
  return user
    ? user
    : {
        email: "",
        firstName: "",
        lastName: "",
        customerId: "",
        id: "",
        role: ""
      };
}

【讨论】:

    【解决方案2】:

    我认为您需要将 useState(InputFields(selectedUser)) 更改为

    useState(() => InputFields(selectedUser))
    

    这样它就不会在每次渲染中都使用初始状态

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多