javascript - TypeError:无法访问属性“错误”,数据未定义
问题描述
得到标题错误并且无法修复它:(。我正在尝试从注册页面获取数据,这是我的 javascript 代码:
const SignupComponent = () => {
const [values, setValues] = useState({
name: 'ryan',
email: 'ryan@gmail.com',
password: 'rrrrrr',
error: '',
loading: false,
message: '',
showForm: true
});
const { name, email, password, error, loading, message, showForm } = values;
const handleSubmit = e => {
e.preventDefault();
// console.table({ name, email, password, error, loading, message, showForm });
setValues({ ...values, loading: true, error: false });
const user = { name, email, password };
signup(user).then(data => {
if(data.error) {
setValues({ ...values, error: data.error, loading: false });
} else {
setValues ({ ...values, name: '', email: '', password: '', error: '', loading: false, message: data.message, showForm: false});
}
});
};
const handleChange = name => e => {
setValues({ ...values, error: false, [name]: e.target.value })
,所以当我尝试在页面中注册时,它说 TypeError: can't access property "error", data is undefined。
signup(user).then(data => {
> 25 | if(data.error) {
| ^
26 | setValues({ ...values, error: data.error, loading: false });
27 | } else {
注册功能
export const signup = (user) => {
return
fetch(${API}/signup, { method: 'POST',
headers: { Accept: 'application/json',
'Content-Type': 'application/json' },
body: JSON.stringify(user) })
.then(response => { return response.json(); })
.catch(err => console.log(err));
我在编程方面有点菜鸟,但我已经在互联网上寻找解决方案,没有任何效果
解决方案
尝试如下重写您的signup()
函数。我猜你错过了反引号,因为我已经以类似的方式实现了 SignUp 并且它对我有用。让我知道它是否有帮助:
export const signup = (user) => {
return fetch(`${API}/signup`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
PS:你不需要使用async/await
,因为你正在使用 Promises with .then()
,也不需要在.then()
里面再链接一个,signup()
因为你已经在handleSubmit()
你调用的地方这样做了signup()
。
推荐阅读
- json - Ubuntu:加载共享库时出错:libqjsonrpc.so.1
- javascript - html 文件中的表单数据未链接到 .js 文件
- mysql - MySQL LEFT JOIN 仅 1 行取决于 MAX() 值
- python - 使用和不使用换行符的 Python 打印
- sql - SQL Server - 选择查询 - 内部联接 - 错误消息:无法解决排序规则冲突
- angular - 如何从服务器端构建与 Angular 路由对应的路由?
- database - 在eclipse中运行jbmp示例时出现问题
- javascript - 如何将 json 数组从 html 文件的脚本部分传递到 javascript 索引?
- python - 根据python中的依赖费用计算销售价格
- h2o - 对枚举/分类类型列求和时,h2o 数据框 GroupBy 和函数在做什么?