Javascript 即使我没有尝试渲染对象,获取对象作为React子错误也是无效的
正如标题所述,我正在发出一个api请求,然后返回一个组件,其中包含api请求的内容作为道具。然而,idk解释了为什么我一直得到这个错误Javascript 即使我没有尝试渲染对象,获取对象作为React子错误也是无效的,javascript,reactjs,Javascript,Reactjs,正如标题所述,我正在发出一个api请求,然后返回一个组件,其中包含api请求的内容作为道具。然而,idk解释了为什么我一直得到这个错误 App.js showPicture = async () =>{ //console.log(KEY) const response = await picOfTheDay.get('',{ params: { date:this.date,
App.js
showPicture = async () =>{
//console.log(KEY)
const response = await picOfTheDay.get('',{
params: {
date:this.date,
hd: true,
api_key: 'KEY'
}
});
//console.log()
this.setState({picDayFullDescription: response}, ()=>{
return <PictureOfTheDay date = {this.state.date} picture= {this.state.picDayFullDescription.url} description={this.state.picDayFullDescription.explanation} />
})
}
render(){
return(
<div>
{/* <PictureOfTheDay date = {this.state.date} picture= {this.state.picDayFullDescription.url} description={this.state.picDayFullDescription.explanation}/> */}
{this.showPicture()}
</div>
)
}
App.js
showPicture=async()=>{
//console.log(键)
const response=wait picofday.get(“”{
参数:{
日期:这个日期,
高清:是的,
api_键:“键”
}
});
//console.log()
this.setState({picDayFullDescription:response},()=>{
返回
})
}
render(){
返回(
{/* */}
{this.showPicture()}
)
}
PictureOfTheDay.js
类PictureOfTheDay扩展了React.Component{
建造师(道具){
超级(道具);
}
render(){
返回(
你好
)
}
}
有人能给我指出正确的方向吗?与其在渲染中调用函数,我宁愿将组件放在渲染中,然后在某个生命周期挂钩(如
componentDidMount
)上调用fetch函数
这将更新状态,从而重新呈现组件和当天的图片。。。如果组件不使用空描述等,这可能是您希望确保字段存在的原因,请根据所需信息有条件地呈现它,例如{this.state.picDayFullDescription&&…}
//App.js
componentDidMount(){
这是showPicture();
}
showPicture=async()=>{
const response=wait picofday.get(“”{
参数:{
日期:这个日期,
高清:是的,
api_密钥:“密钥”,
},
});
this.setState({picDayFullDescription:response});
}
render(){
返回(
);
}
与其在呈现中调用函数,不如将组件放在呈现中,然后在某个生命周期挂钩上调用fetch函数,如componentDidMount
这将更新状态,从而重新呈现组件和当天的图片。。。如果组件不使用空描述等,这可能是您希望确保字段存在的原因,请根据所需信息有条件地呈现它,例如{this.state.picDayFullDescription&&…}
//App.js
componentDidMount(){
这是showPicture();
}
showPicture=async()=>{
const response=wait picofday.get(“”{
参数:{
日期:这个日期,
高清:是的,
api_密钥:“密钥”,
},
});
this.setState({picDayFullDescription:response});
}
render(){
返回(
);
}
如果您想得到帮助,您需要发布一个最小的、可复制的示例。你的例子是不可复制的。你在App.js中缺少组件的类声明,除此之外,我没有太多其他的代码,包括类声明和一些关于当前日期的代码。我认为我遗漏的东西对我的问题或代码没有影响。在我看来,上面的代码应该不会给我带来任何问题,但出于某种原因,它一直给我这个错误。“我遗漏的东西我相信不会对我的问题或代码产生影响”如果它对问题产生影响,这并不重要。如果需要重现问题,因为没有它它无法编译/运行,那么您需要发布它。this.showPicture()
返回一个承诺。将其从JSX中删除。这意味着,您需要在componentDidMount
或componentdiddupdate
中执行异步操作,并在render
函数中使用this.state
。如果需要帮助,您需要发布一个最小的、可复制的示例。你的例子是不可复制的。你在App.js中缺少组件的类声明,除此之外,我没有太多其他的代码,包括类声明和一些关于当前日期的代码。我认为我遗漏的东西对我的问题或代码没有影响。在我看来,上面的代码应该不会给我带来任何问题,但出于某种原因,它一直给我这个错误。“我遗漏的东西我相信不会对我的问题或代码产生影响”如果它对问题产生影响,这并不重要。如果需要重现问题,因为没有它它无法编译/运行,那么您需要发布它。this.showPicture()
返回一个承诺。将其从JSX中删除。这意味着您需要在componentDidMount
或componentdiddupdate
中执行异步操作,并在render
函数中使用this.state
。
PictureOfTheDay.js
class PictureOfTheDay extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<div>
Hello?
</div>
)
}
}