【问题标题】:why does this error occur during fetch data from the backend为什么在从后端获取数据时会出现此错误
【发布时间】:2020-11-11 05:23:24
【问题描述】:

当我尝试使用下面创建的方法登录时,登录组件出现问题。

下面是代码示例:

export default function Signin(props) {
    const classes = useStyles();
    const [values, setValues] = useState({
        email: '',
        password: '',
        error: '',
        redirectToReferrer: false,
    });

    const handleSubmit = () => {
        const user = {
            email: values.email || undefined,
            password: values.password || undefined,
        };

        signin(user).then((data) => {
            if (data.error) {
                setValues({ ...values, error: data.error });
            } else {
                auth.authenticate(data, () => {
                    setValues({ ...values, error: '', redirectToReferrer: true });
                });
            }
        });
    };

    const handleChange = (name) => (event) => {
        setValues({ ...values, [name]: event.target.value });
    };

    const { from } = props.location.state || {
        from: {
            pathname: '/',
        },
    };

    const { redirectToReferrer } = values;
    if (redirectToReferrer) {
        return <Redirect to={from} />;
    }
}

如果我保存此代码,则会出现错误:

无法读取未定义的属性状态。

当我注释掉这个 {from} 时,会出现登录表单。但是当我点击提交按钮时出现另一个错误:

无法读取未定义的属性错误。

这是我的登录方法:

const signin = async (user) => {
    try {
        let response = await fetch('http://localhost:4000/auth/signin', {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            credentials: 'include',
            body: JSON.stringify(user),
        });
        return await response.json();
    } catch (err) {
        console.log(err);
    }
};

和认证方法:

const auth = {

    authenticate(jwt, cb) {
        if (typeof window !== 'undefined')
            sessionStorage.setItem('jwt', JSON.stringify(jwt));
        cb();
    },
};

export default auth;

【问题讨论】:

  • can not read property state of undefined,解决这个问题props.location &amp;&amp; props.location.state || ...
  • @Naren 解决了。非常感谢兄弟
  • 很高兴,成功了!!

标签: reactjs authentication fetch jwt-auth


【解决方案1】:

查看您的代码后,我看到这两个地方可能会出错:

props.location.state and data.error.

要解决can not read property state of undefined,再添加一项安全检查:

const { from } = props.location && props.location.state || {
    from: {
        pathname: '/',
    },
};

对于这个:cannot read property error of undefined

signin(user).then((data) => {
   if (data && data.error) {
      setValues({ ...values, error: data.error });
   } else {
      auth.authenticate(data, () => {
         setValues({ ...values, error: '', redirectToReferrer: true });
      });
  }
});

【讨论】:

    猜你喜欢
    • 2011-09-19
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2021-08-04
    • 1970-01-01
    • 2023-01-29
    • 2019-10-06
    相关资源
    最近更新 更多