运行 尝试更改输入 onChange 时进入状态错误

Running into a state error when attempting to change an input onChange

当我从父组件向下传递状态时,setState 不断抛出错误,指出 setEmail 不是事件更改的函数。我想知道是否有一个简单的解决方法。

当我尝试在电子邮件输入中输入字符串时,它会抛出以下错误:

Error: Unhandled Runtime Error TypeError: setEmail is not a function

父组件:(Next.js 应用程序)

import React, { useState, useContext, useEffect } from "react";
import "../styles/globals.css";
import "bootstrap/dist/css/bootstrap.min.css";

function MyApp({ Component, pageProps }) {
  const [tester, setTester] = useState(false);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  return (
    <Component
      {...pageProps}
      email={email}
      setEmail={setEmail}
      password={password}
      setPassword={setPassword}
    />
  );
}

export default MyApp;

子组件:

export default function Signup(props) {
  const router = useRouter();
  
  const { email, setEmail, password, setPassword, setHasAccount } = props;

// function to handle submitting a new user on click
  const onSubmit = (event) => {
    event.preventDefault();
    router.push("/questions");

  };
  return (
    <div>
      <div>
        <Container>
          <form onSubmit={onSubmit} className={styles.formSize}>
            <FormGroup>
              <Input
                className={styles.inputContainer}
                value={email}
                placeholder="john.doe@example.com"
                onChange={(e) => setEmail(e.target.value)}
              />
              <Input
                className={styles.inputContainer}
                placeholder="password"
                value={password}
                onChange={(event) => setPassword(event.target.value)}
              />
              <Button color="primary" type="submit">
                Signup
              </Button>
              <p
                className={styles.loginPhrase}
                onClick={(event) => {
                  event.preventDefault();
                  setHasAccount(true);
                }}
              >
                Have an account? Login Here
              </p>
            </FormGroup>
          </form>
        </Container>
      </div>
      <link rel="icon" href="/favicon.ico" />
    </div>
  );
}

您需要检查该组件的父组件是否传入了一个名为 setEmail 的 prop,并且它是一个函数。看来您可能忘记将其作为 prop 传入。

我获取了您的代码并将其移植到沙箱中并且运行良好,我相信您以某种方式错误地传递了 props。这是沙盒的副本,因此您可以看到它的运行情况

https://codesandbox.io/s/gallant-microservice-yig2q?file=/src/App.js