【问题标题】:Unhandled Rejection (TypeError): appUser is not iterable未处理的拒绝(TypeError):appUser 不可迭代
【发布时间】:2019-11-30 00:11:42
【问题描述】:

我正在尝试将来自我的 rest api 的响应设置为 React 状态。我试着这样做,就像我在这篇 SO 帖子中读到的那样:useState object set

这是我尝试过的:

Admin.js

import React, {useState} from "react";
import {Button} from "../components/AuthForms"
import {useAuth} from "../context/auth";
import axios from 'axios';

function Admin(props) {

    ...

    const [username, setUsername] = useState(null);
    const [appUser, setAppUser] = useState({pk:-1, username: '', email: '', first_name: '', last_name:''});
    const key = !authTokens ? "Logged out" : authTokens.key;


    if (!!authTokens) {
        const url = 'http://localhost:8000/rest-auth/user/';
        const withCredentials = true;
        const method = 'get';
        axios.request({method, url, withCredentials}).then(response => {
            console.log('Admin() response is ', response);
            setUsername(response.data.username);
            setAppUser(...appUser, response.data); <==== here's where I get the error.
        });

    ...

    // display the logged in user info.
    return (
        <div>
            <div>Admin Page</div>
            <div>Key: {key}</div>
            <div>Username: {username}</div>
            <div>App User pk: {appUser.pk} username: {appUser.username}</div>
            <Button onClick={logOut}>Log out</Button>
        </div>);
}

export default Admin;

appUser应该如何设置?

谢谢

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    你忘记了对象括号:

     setAppUser({...appUser, ...response.data})
    

    也将其放在useEffect 中,以便仅在authTokens 更改时获取数据:

    useEffect(()=>{
        if (authTokens) {
            const url = 'http://localhost:8000/rest-auth/user/';
            const withCredentials = true;
            const method = 'get';
            axios.request({method, url, withCredentials}).then(response => {
                console.log('Admin() response is ', response);
                setUsername(response.data.username);
                setAppUser({...appUser, response.data}); <==== here's where I get the error.
            });
    }, [authTokens]); // The [authTokens] means, that it will only fetch the data again if authTokens changes
    

    还有你为什么要!!authTokens?您可以删除!!

    【讨论】:

    • setAppUser({...appUser, response.data}); 给了我Parsing error: Unexpected token, expected ","!! 来自其他开发人员。
    • 而做setAppUser({...appUser}, response.data);似乎造成了无限循环。
    • 是同一行引起的吗?你确定你输入正确了吗?我通过简单的优化进一步编辑了帖子。
    • setAppUser({...appUser, ...response.data}); 有效吗?我更新了我的帖子。
    • 谢谢。这就是诀窍。我确实收到警告`第 43:8 行:React Hook useEffect 缺少依赖项:'appUser'。包括它或删除依赖数组。如果您只需要“setAppUser”中的“appUser”,您也可以进行功能更新“setAppUser(a => ...)”`
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    • 2021-02-27
    • 1970-01-01
    • 2022-01-03
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多