大家好,我正试图在我的应用程序中使用钩子,但它一直在说未处理的拒绝(不变冲突(:钩子只能在函数组件内部调用。我猜我的一个库与钩子冲突,因为我找不到任何代码问题。
这是我的包.json,我正在迁移从重新组合到钩子的所有内容。。。我曾在一个测试项目中尝试将钩子与nex.js一起使用,结果很好。。。
{
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "^7.0.2",
"next-images": "^1.0.1",
"react": "^16.7.0-alpha.2",
"react-dom": "^16.7.0-alpha.2",
"recompose": "^0.30.0",
"styled-components": "^4.1.1"
},
"devDependencies": {
"babel-plugin-styled-components": "^1.9.0",
"eslint": "^5.9.0",
"eslint-plugin-react": "^7.11.1",
"eslint-plugin-react-hooks": "^0.0.0"
}
}
这是我的代码:
import Layout from "../components/Layout";
import Head from "next/head";
import Register from "../blocks/Register";
import InputBox from "../components/InputBox";
import regexUtils from "../utils/regexUtils";
import { useState } from "react";
function BaseComponent() {
const { errors, onSubmit } = useOnSubmit();
const [name, setName] = useHandleInputChange("");
const [email, setEmail] = useHandleInputChange("");
const [password, setPassword] = useHandleInputChange("");
const [passwordAgain, setPasswordAgain] = useHandleInputChange("");
return (
<Layout>
<Head>
<title>Sheet Builder - Register your account</title>
</Head>
<Register>
<Register.Center>
<form>
<Register.Box>
<Register.Title>Create Account</Register.Title>
<InputBox error={errors.name} value={name} onChange={setName}>Your Name</InputBox>
<InputBox error={errors.email} value={email} onChange={setEmail}>Email</InputBox>
<InputBox error={errors.password} value={password} onChange={setPassword} mask>Password</InputBox>
<InputBox error={errors.passwordAgain} value={passwordAgain} onChange={setPasswordAgain} mask hint="Passwords must consist of at least 8 characters.">Password Again</InputBox>
<Register.Button onClick={onSubmit} type="submit" value="Register your Sheet Builder account" />
</Register.Box>
</form>
</Register.Center>
</Register>
</Layout>
);
}
function useHandleInputChange(initialState) {
const [value, setValue] = useState(initialState);
const handleInputChange = (e) => {
setValue(e.target.value);
};
return [value, handleInputChange];
}
function useOnSubmit() {
const initialState =
{
email: false,
name: false,
password: false,
passwordAgain: false
};
const [errors, setErrors] = useState(initialState);
const onSubmit = (e)=>{
e.preventDefault();
let result = {};
result.email = !regexUtils.isEmailFormatValid(errors.email);
result.name = !regexUtils.isFormatValid(errors.name);
result.password = !regexUtils.isPasswordFormatValid(errors.password);
result.passwordAgain = !regexUtils.isPasswordFormatValid(errors.passwordAgain);
setErrors(result);
};
return {
errors,
onSubmit
};
}
export default BaseComponent;
看起来Microsoft visual studio代码调试器有一个错误。我从命令行运行了这个程序,之后它运行得很好。
您需要导入react,以便将函数视为react功能组件
import React, {useState} from 'react';
阅读此博客文章以了解为什么要从功能组件中的"React"导入React?