【问题标题】:error: Cannot set properties of undefined when setting the value of nested object错误:设置嵌套对象的值时无法设置未定义的属性
【发布时间】:2021-09-08 09:48:54
【问题描述】:

我想将errors的值设置为

{
  email: {
    primary:"abc@gmail.com"
  }
}

编译后返回错误:

Cannot set properties of undefined (setting 'primary')

App.js

import "./styles.css";
import { useState, useEffect } from "react";

export default function App() {
  const [errors, setErrors] = useState({});

  useEffect(() => {
    const newErrors = errors;
    newErrors.email.primary = "abc@gmail.com";
  }, []);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

代码沙盒:
https://codesandbox.io/s/immutable-http-w0mue?file=/src/App.js

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    因为newErrors.emailundefined。像这样更新:

    newErrors.email = { primary: "abc@gmail.com" };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2019-10-14
      • 2022-10-30
      相关资源
      最近更新 更多