错误:设置嵌套对象的值时无法设置未定义的属性

CCC*_*CCC 7 javascript reactjs

我想将 的值设置errors

{
  email: {
    primary:"abc@gmail.com"
  }
}
Run Code Online (Sandbox Code Playgroud)

编译后,返回错误:

Cannot set properties of undefined (setting 'primary')
Run Code Online (Sandbox Code Playgroud)

应用程序.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>
  );
}

Run Code Online (Sandbox Code Playgroud)

Codesandbox:
https://codesandbox.io/s/immutable-http-w0mue?file=/ src/App.js

Vie*_*iet 12

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

newErrors.email = { primary: "abc@gmail.com" };
Run Code Online (Sandbox Code Playgroud)