【问题标题】:Running into a state error when attempting to change an input onChange尝试更改输入 onChange 时遇到状态错误
【发布时间】:2021-01-16 09:56:45
【问题描述】:

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

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

错误:未处理的运行时错误 TypeError: setEmail 不是一个函数

父组件:(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>
  );
}

【问题讨论】:

  • 能不能显示Signup的父组件
  • 抱歉,添加了父组件信息,它是一个 next.js 应用程序,所以它是 _app.tsx

标签: javascript reactjs next.js use-state


【解决方案1】:

我把你的代码移植到一个沙箱中,它工作得很好,我相信你以某种方式错误地传递了道具。这是沙盒的副本,您可以看到它正在运行

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-07-02
      • 2021-09-18
      • 2022-10-16
      • 1970-01-01
      • 2015-11-17
      • 1970-01-01
      • 2018-09-16
      • 2019-12-09
      • 2020-01-28
      相关资源
      最近更新 更多