我正在尝试将我的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?
谢谢
答案 0 :(得分: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
呢?您可以删除!!
。