在上下文提供商中使用状态设置在组件中获取调用
我有一个上下文提供商,在其中进行了调用以获取当前的用户ID,然后将其设置为在其他组件中使用的状态。
export const CurrentUserProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null)
const fetchCurrentUser = async () => {
let response = await fetch("http://127.0.0.1:5000/dj-rest-auth/user/", authRequestOptions('GET'))
response = await response.json()
setCurrentUser(response.pk)
}
return (
<CurrentUserContext.Provider value={{ currentUser, fetchCurrentUser }}>
{children}
</CurrentUserContext.Provider>
)
}
export const useCurrentUser = () => useContext(CurrentUserContext)
我的目标是,在页面加载时,请在组件中调用fetchcurrentuser,然后使用由此作为另一个API调用的一部分设置的当前使用者状态。我在下面尝试过的内容:
useEffect(() => {
fetchCurrentUser()
}, [])
useEffect(() => {
fetch(`http://127.0.0.1:5000/api/user-conversation-brief/${currentUser}`, requestOptions('GET'))
.then(response => response.json())
.then(data => {
setSideBarMessages(data)
setLoading(true)
})
.catch(error => console.log(error))
}, [currentUser])
但这在初始页面渲染上不起作用。我将如何按预期运行?
I have a context provider within which a fetch call is made to get the current user ID and then set it as state to use in my other components.
export const CurrentUserProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null)
const fetchCurrentUser = async () => {
let response = await fetch("http://127.0.0.1:5000/dj-rest-auth/user/", authRequestOptions('GET'))
response = await response.json()
setCurrentUser(response.pk)
}
return (
<CurrentUserContext.Provider value={{ currentUser, fetchCurrentUser }}>
{children}
</CurrentUserContext.Provider>
)
}
export const useCurrentUser = () => useContext(CurrentUserContext)
My goal is to, on page load, call fetchCurrentUser in a component and then use the currentUser state that is set as a result of that as part of another API call. What I've tried below:
useEffect(() => {
fetchCurrentUser()
}, [])
useEffect(() => {
fetch(`http://127.0.0.1:5000/api/user-conversation-brief/${currentUser}`, requestOptions('GET'))
.then(response => response.json())
.then(data => {
setSideBarMessages(data)
setLoading(true)
})
.catch(error => console.log(error))
}, [currentUser])
But this doesn't work on the initial page render. How would I go making it work as intended?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论