首页 > 解决方案 > 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));

我在编程方面有点菜鸟,但我已经在互联网上寻找解决方案,没有任何效果

标签: javascriptnode.jsreactjsmongodbnext.js

解决方案


尝试如下重写您的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()


推荐阅读