在componentDidMount()中,我获取数据并将其传递给状态。
componentDidMount() {
const url = fetch('http://localhost:8000/posts/')
.then(response => response.json())
.then(response => {
this.setState({ data: response });
})
}
接下来我尝试获取this.state.data[0].id
的数据
在这种情况下,我收到错误
TypeError: cannot read property 'id' of undefined
但是如果我尝试通过 this.state.data[0]
获取数据,则会出现一个对象,其中有一个属性 id
最佳答案
您正在从远程源获取数据,并且此获取操作是异步的。在应用程序的初始渲染中,您还没有此数据。componentDidMount
触发提取,您的数据会进入您的应用程序。因此,您应该按照评论中的建议使用条件渲染。这是一个简单的例子:
class App extends React.Component {
state = {
posts: []
};
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(posts => {
this.setState({ posts });
});
}
render() {
const { posts } = this.state;
return <div>{!!posts.length && posts[0].title}</div>;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
并且有一点增强。因为我非常确定您不会在应用程序中使用单个数据项。作为将来的引用,您可以使用这个简单的逻辑。更好的方法是重构此代码并编写单独的 Post
组件。
class App extends React.Component {
state = {
posts: []
};
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(posts => {
this.setState({ posts });
});
}
render() {
const { posts } = this.state;
if (!posts.length) return <p>Loading...</p>;
return (
<div>
{posts.map(post => (
<div key={post.id}>
<p>{post.title}</p>
</div>
))}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
关于javascript - ReactJs:无法访问对象元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53823296/