首页 > 解决方案 > 使用数据返回未定义更新状态

问题描述

我有一个名为 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}返回正确

标签: reactjs

解决方案


试试这样

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);
            });

推荐阅读