我已经定义了错误。但是,它给出的错误是“TypeError:无法读取未定义的属性'错误'”
我这里有货。我会很感激超越这一点的想法。
感谢您的帮助。
错误截图
注册组件代码
import React , {useState} from 'react';
import { signup } from '../../../actions/auth';
const SignupComponent = () => {
const [values, setValues] = useState({
firstname: '',
lastname: '',
email: '',
phonenumber: '',
password: '',
confirmpassword: '',
howdidyouknowaboutus: '',
error: '',
loading: false,
message: '',
showForm: true
});
const {firstname, lastname, email, phonenumber, password, confirmpassword, howdidyouknowaboutus, error, loading, message, showForm} = values;
const handleSubmit = e => {
e.preventDefault();
/* console.table({firstname, lastname, email, phonenumber, password, confirmpassword,howdidyouknowaboutus,
error, loading, message, showForm}); */
setValues({...values, loading: true, error: false})
const user = {firstname, lastname, email, phonenumber, password, confirmpassword, howdidyouknowaboutus}
signup(user).then(data => {
if (data.error) { ----------------------------------------------- The line with the error
setValues({...values, error: data.error, loading: false});
}else{
setValues({
...values,
firstname: '',
lastname: '',
email: '',
phonenumber: '',
password: '',
confirmpassword: '',
howdidyouknowaboutus: '',
error: '',
loading: false,
message: data.message,
showForm: false
});
}
});
};
};
export default SignupComponent;
谢谢
答案 0 :(得分:1)
UPD
signup(user).then(data => {
if (data) { // check here if data not undefined
if (data.error) {
setValues({...values, error: data.error, loading: false});
}else{
setValues({
...values,
firstname: '',
lastname: '',
email: '',
phonenumber: '',
password: '',
confirmpassword: '',
howdidyouknowaboutus: '',
error: '',
loading: false,
message: data.message,
showForm: false
});
}
} else {
// probably here you would need to do something if dada is undefined
}
});
之前的回复
改成
if (data && data.error)
确保数据已定义
答案 1 :(得分:0)
Console.log(data) 首先检查响应,也许屏幕截图并发布服务进行注册,因为任何接收到的数据都将来自服务本身的响应。 确保您也能发现注册服务中的错误。
更新
在您的 API 中,您可以使用以下内容捕获错误:
Test
然后在您的前端:
return res.status(400).json({
errorMessage: "Username already taken",
});
}
并且在您的 API 调用中,您可以使用以下内容捕获错误:
function internalServerError(err) {
if (err.response && err.response.data && err.response.data.errorMessage) {
return {
status: false,
errorMessage: err.response.data.errorMessage,
};
}
return {
status: false,
errorMessage: "Internal server error. Please check your server",
};
}
答案 2 :(得分:0)
谢谢。这项工作。但是,对后端的 post 请求正在等待,检查网络捕获。控制台没有错误。然而,pending 是指向这个代码
import fetch from 'isomorphic-fetch';
import {API} from '../config';
export const signup = (user) => {
return fetch(`${API}/signup`, { ----- pending status pointing to this line
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json()
})
.catch(err => console.log(err));
};