【发布时间】:2021-02-11 09:36:08
【问题描述】:
我是新手,在搜索和弄乱代码后找不到答案。我在 useEffect 挂钩内向我的服务器发出 get 请求,并尝试获取响应并将其设置为一个状态。我正确地从服务器取回响应,但由于某种原因,我无法获取响应并将其设置为某种状态(下面的 setProfile 什么都不做)。代码如下:
const Profile = () => {
const [profile, setProfile] = useState(null);
const { state, dispatch } = useContext(UserContext);
const { userid } = useParams();
useEffect(() => {
fetch(`/user/${userid}`, {
headers: {
Authorization: 'Bearer ' + localStorage.getItem('jwt'),
},
})
.then((res) => res.json())
.then((result) => {
setProfile(result);
});
}, []);
令人费解的是,我能够在类似的 get 请求中很好地设置状态:
const Profile = () => {
const [mypics, setPics] = useState([]);
const { state, dispatch } = useContext(UserContext);
useEffect(() => {
fetch('/myposts', {
headers: {
Authorization: 'Bearer ' + localStorage.getItem('jwt'),
},
})
.then((res) => res.json())
.then((result) => {
setPics(result.myposts);
});
}, []);
任何帮助将不胜感激。
【问题讨论】:
-
您是否收到错误消息?
-
没有错误信息。我的组件加载正常。
-
你的代码对我来说很好。
-
谢谢。你是对的,我这里显示的代码很好,我犯了一个错误,试图在更新之前读取状态。
标签: reactjs react-hooks state use-effect