Reactjs 如果尚未从状态加载项,则阻止渲染尝试
我要求cloudinary提供一张图片,从表面上看,一切都很好,因为我可以在前端看到预期的图片。但是当查看chrome开发工具时,我可以看到首先出现了一个404错误,显示了对存储图像的路径的调用,但没有图像名称。对于成功的第二个调用,有路径和映像名称 因此,似乎在图像名称尚未从发出第一个请求时的状态加载之前。我确实尝试了&&条件检查,但结果相同,即:Reactjs 如果尚未从状态加载项,则阻止渲染尝试,reactjs,cloudinary,Reactjs,Cloudinary,我要求cloudinary提供一张图片,从表面上看,一切都很好,因为我可以在前端看到预期的图片。但是当查看chrome开发工具时,我可以看到首先出现了一个404错误,显示了对存储图像的路径的调用,但没有图像名称。对于成功的第二个调用,有路径和映像名称 因此,似乎在图像名称尚未从发出第一个请求时的状态加载之前。我确实尝试了&&条件检查,但结果相同,即: {this.state.bgImg && this.state.bgImg} 然后我试着: {this.state.bgImg
{this.state.bgImg && this.state.bgImg}
然后我试着:
{this.state.bgImg ? this.state.bgImg : "fakeImage.jpg"}
在开发工具中,我看到它实际上试图获取fakeImage.jpg
我怎样才能防止这种情况
class Home extends Component {
state = {
title: "",
bgImg: "",
categories: []
};
async componentDidMount() {
const response = await getHero();
const { data: categories } = await getCategories();
this.setState({
title: response.data.title,
categories,
bgImg: response.data.bgImg
});
}
render() {
return (
<React.Fragment>
<NavBar />
<Hero
title={this.state.title}
bgImg={this.state.bgImg && this.state.bgImg}
/>
</React.Fragment>
);
}
}
export default Home;
const imageUrl = process.env.REACT_APP_CLOUDINARY_URL;
class Hero extends Component {
render() {
const { title, bgImg } = this.props;
return (
<section
className="section-hero d-flex justify-content-center align-items-center mb-5"
style={{
backgroundImage: `linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2)), url(${imageUrl}/somepath/${bgImg})`
}}
>
<Container className="text-center text-white">
<h1>{title}</h1>
</Container>
</section>
);
}
}
export default Hero;
对于主组件的初始渲染,将空字符串传递给bgImg道具的Hero。您将收到404错误,因为在此路径中未找到图像
url(${imageUrl}/somepath/${bgImg}) <--- bgImg is an empty string on first render.
我们需要了解您是如何从Cloudinary获取图像的。您的帖子中这些片段的上下文是什么?它们是否在img标签的src道具中?如果图像丢失,即{this.state.bgImg?:null}?@user8463989,请尝试下面的解决方案,让我知道这是否有帮助:
class Home extends Component {
state = {
title: "",
bgImg: null,
categories: []
};
async componentDidMount() {
const response = await getHero();
const { data: categories } = await getCategories();
this.setState({
title: response.data.title,
categories,
bgImg: response.data.bgImg
});
}
render() {
const { bgImg } = this.state
return (
<React.Fragment>
<NavBar />
{ bgImg && (
<Hero
title={this.state.title}
bgImg={bgImg}
/>
)}
</React.Fragment>
);
}
}
export default Home;