reactjs - 使用数据返回未定义更新状态
问题描述
我有一个名为 data 的状态,它是空对象 state={data:{}} 我在控制台记录时调用了 RestAPI 更新状态 USING set state,它以正确的格式返回数据,但我需要的数据是 this.state.data。 title.rendered 它说未定义,但在控制台日志中它有数据 Rest Api 是这样的:
{id:5,title:{rendered:"home is good"}}
fetch(`http://localhost/react-wordpress/wp-json/wp/v2/posts/${this.props.match.params.id}`)
.then((response) => response.json())
.then((responseJson) => {
const { title, fimg_url, content } = responseJson;
this.setState({ title, fimg_url, content });
this.setState({ data: responseJson })
})
.catch((error) => {
console.error(error);
});
在呈现的方法{this.state.data.title.rendered}
中返回未定义而{this.state.title.rendered}
返回正确
解决方案
试试这样
fetch(`http://localhost/react-wordpress/wp-json/wp/v2/posts/${this.props.match.params.id}`)
.then((response) => response.json())
.then((responseJson) => {
const { title, fimg_url, content } = responseJson;
this.setState({ data: {title, fimg_url, content} });
})
.catch((error) => {
console.error(error);
});
推荐阅读
- python - PyQt5:为什么我的 QGraphicsVideoItem 播放后消失?是否可以在最后一帧暂停 QMediaPlayer?
- ms-access-2016 - 运行时错误“3078”:Microsoft Access 数据库引擎找不到输入表
- flutter - Flutter graphql缓存更新只工作一次
- powershell - POST请求变量powershell
- c++ - Linux下Mapbox编译离线工具
- xamarin.forms - 如何减小 SwipeItem 图标图像大小
- css - 图片:不透明度悬停在我的固定标题后面?
- php - 在 Ajax 回调中使用 WordPress 自定义图像大小
- python - 如果python中的某些条件,将字符串附加到上一行
- arm-template - 如何使用ARM模板导出导入突触专用Sql池