3 回答
TA贡献1783条经验 获得超4个赞
这里最好的解决方案是在上下文提供程序中添加一个加载状态,一旦值更新就会重置。
function Profile(props) {
const {userinfo, loading, setuserinfo}=useContext(Userinfo);
useEffect(()=>{
if(!loading) {
((userinfo==null)?
/*API call A (When user is not logged in) */ :
/*API call B (When user is logged in) */
)
}
)},[loading, userinfo])
if(loading) return <Loader />
return (
(userinfo==null)?
/*Elements to render when user is not logged in) */ :
/*Elements to render when user is logged in) */
);
}
TA贡献1796条经验 获得超4个赞
我今天遇到了这个问题,我喜欢 Shubham 的做法。但是我解决它的方法只是userinfo从前一个组件中获取并将其传递给这个配置文件组件。
但是,请确保您Profile像这样渲染组件,以便确保userinfo存在:
function ParentComponent(){
// do sth to get the userinfo here
return(
<ParentComponent>
{userinfo? <Profile userinfo={userinfo} /> : null}
<ParentComponent/>
)
}
TA贡献1815条经验 获得超6个赞
假设您正在设置如下上下文:
import React from 'react';
const AuthContext = React.createContext({
userInfo: null,
isLoggedIn: false,
loading: true,
setUser: () => {}
});
export default AuthContext;
您正在像这样设置您的全球提供商:
import React from 'react';
import AuthContext from './AuthContext'; // path to the context
export default class GlobalUserContext extends React.Component{
constructor(props){
super(props);
this.state = {
userInfo: null,
isLoggedIn: false,
loading: true
}
}
componentDidMount(){
( async() => {
const currentUser = await getUser(); // say you are trying to log user in
if(currentUser){
this.setState({
userinfo: currentUser,
isLoggedIn: true,
loading: false
});
}
} )();
}
setUser = (user, check) => {
this.setState({userInfo: user, isLoggedIn: check});
};
render(){
return (
<AuthContext.Provider
value={{
user: this.state.user,
setUser: this.setUser,
isLoggedIn: this.state.isLoggedIn,
loading: this.state.loading
}}>
{this.props.children}
</AuthContext.Provider>
);
}
}
然后在使用的功能组件中useEffect,您可以执行以下操作:
import React, { useContext, useEffect} from 'react';
import AuthContext from '../../contexts/AuthContext'; // your content path
export const MyComponent = () => {
const {userInfo, isLoggedIn, loading} = useContext(AuthContext);
useEffect(() => {
// here you can now ask if the user data is still loading like so:
if(!loading){
// do something
// UserInfo is available
}
}, [userInfo, loading]);
return (
<View>
{anything}
</View>
);
}
添加回答
举报