Javascript React.js this.props未定义,除非页面刷新
因此,我有以下问题,我试图显示用户在用户配置文件中发表的所有帖子。如果我从登录开始并转到配置文件,它会给我一个错误,即this.props.user[0].id未定义。但是,如果我刷新页面(有时两次),它就可以完美地工作 我有在线搜索,我只看到相反的情况(刷新时道具未定义),我无法找到解决方案 这是我的代码:Javascript React.js this.props未定义,除非页面刷新,javascript,reactjs,react-props,Javascript,Reactjs,React Props,因此,我有以下问题,我试图显示用户在用户配置文件中发表的所有帖子。如果我从登录开始并转到配置文件,它会给我一个错误,即this.props.user[0].id未定义。但是,如果我刷新页面(有时两次),它就可以完美地工作 我有在线搜索,我只看到相反的情况(刷新时道具未定义),我无法找到解决方案 这是我的代码: 从“React”导入React; 从“axios”导入axios; 从“reactstrap”导入{Card,CardBody,CardTitle,CardText}; 从“/Withu
从“React”导入React;
从“axios”导入axios;
从“reactstrap”导入{Card,CardBody,CardTitle,CardText};
从“/Withuser”导入Withuser
类概要文件扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
想法:[]
}
}
componentDidMount=()=>{
这个文件名为getShares()
}
getShares=()=>{
const user\u id=this.props.user[0].id
console.log(this.props.user[0].id)
axios(`http://localhost:7001/api/profile/shares/${user\u id}`)
。然后(res=>{
console.log(res.data)
this.setState(state=>({
想法:资源数据,
loggedIn:!state.loggedIn
}))
})
.catch(错误=>{
this.setState({error:true})
})
}
render(){
const{thinks}=this.state
返回(
你的帖子
{thinks.map((思想,索引)=>{
返回(
{think.user_name}发布在{think.createdAt}
{思想.身体}
)
})}
)
}
}
使用用户导出默认值(配置文件,{renderNull:true})代码>
可以通过向HOC添加加载状态来修复此问题,以便在获取数据之前不呈现包装的组件
const withUser = (Component, options = { renderNull: true }) => props => {
const [userData, setUserData] = useState(null);
const [userId, setUserId] = useState(null);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
useEffect(() => {
const token = localStorage.getItem('token');
if (!token) return;
setLoading(true); // set the loading state before api call is made
axios('http://localhost:7001/api/profile', {
headers: {
'x-access-token': token,
},
})
.then(response => {
const id = response.data.id;
setUserId(id);
})
.catch(error => {
setError(true);
console.log(error);
})
.finally(() => {
setLoading(false); // reset loading state after api call is done
});
}, []);
useEffect(() => {
setLoading(true); // set the loading state before api call is made
axios(`http://localhost:7001/api/users/${userId}`).then(response => {
setUserData(response.data);
}).finally(() => setLoading(false)); // reset loading state after api call is done
}, [userId]);
if (loading) return null; // Or render a loading indicator
if (!userData && options.renderNull) return null;
return <Component {...props} user={userData} />;
};
constwithuser=(组件,选项={renderNull:true})=>props=>{
const[userData,setUserData]=useState(null);
const[userId,setUserId]=useState(null);
const[error,setError]=useState(false);
const[loading,setLoading]=useState(false);
useffect(()=>{
const token=localStorage.getItem('token');
如果(!token)返回;
setLoading(true);//在进行api调用之前设置加载状态
axios('http://localhost:7001/api/profile', {
标题:{
“x-access-token”:标记,
},
})
。然后(响应=>{
const id=response.data.id;
setUserId(id);
})
.catch(错误=>{
设置错误(真);
console.log(错误);
})
.最后(()=>{
setLoading(false);//api调用完成后重置加载状态
});
}, []);
useffect(()=>{
setLoading(true);//在进行api调用之前设置加载状态
axios(`http://localhost:7001/api/users/${userId}`)。然后(响应=>{
setUserData(response.data);
}).finally(()=>setLoading(false));//完成api调用后重置加载状态
},[userId]);
if(loading)返回null;//或呈现加载指示符
如果(!userData&&options.renderNull)返回null;
返回;
};
这是因为在useffect中,axios是一个异步调用
const withUser = (Component, options = { renderNull: true }) => props => {
...
useEffect(() => {
axios(`http://localhost:7001/api/users/${userId}`)
.then(response => {
setUserData(response.data)
})
}, [userId])
快速可靠的解决方案是在剖面组件上添加默认道具
Profile.defaultProps = {
user: [],
}
并进行必要的检查
getShares = () => {
if(props.user.length === 0) return
WithUser
HOC看起来怎么样?似乎是从传递到配置文件的内容中得到的。你能用User HOC检查一下吗?谢谢大家,我已经编辑了帖子并添加了Withuser组件。你能把Withuser
组件包括进来吗?仍然没有找到解决这个问题的方法,这有点奇怪,因为如果我对这两个组件中的任何一个做了一些小的更改,比如console.log,它都可以工作,然后我再试一次,它没有…。谢谢@Clarity,我一开始就认为它是假的,但它给了我一个错误,不能读取null属性(而不是未定义的)@Guerreri88啊,我现在明白了。我已经用一个更好的建议编辑了我的答案。谢谢@Clarity,我已经尝试过了,但是我得到了一个错误“无法读取null的属性0”。参考这个。props.userHey Nikko,谢谢你的回答,我一直在阅读有关defaultProps的内容,我仍然不确定如何将它应用到我的应用程序中。我需要这些道具的原因是从登录的用户那里获取用户ID。如何使用defaultProps实现这一点?这对我来说不清楚。。。对不起,我在编码方面有点新…我建议只在初始加载时预先设置未定义,以便允许使用正确的道具进行更新