简体   繁体   English

ReactJs:无法访问对象元素

[英]ReactJs: can't access object element

In componentDidMount (), I get the data and pass it to the state. 在componentDidMount()中,我获取数据并将其传递给状态。

componentDidMount() {
    const url = fetch('http://localhost:8000/posts/')
        .then(response => response.json())
        .then(response => {
            this.setState({ data: response });
        })
}

Next I try to get the data of this.state.data[0].id In this case, I get the error 接下来,我尝试获取this.state.data[0].id的数据,在这种情况下,我得到了错误

TypeError: cannot read property 'id' of undefined TypeError:无法读取未定义的属性“ id”

But if I try to get data through this.state.data[0] , then an object comes in, where there is a property id 但是,如果我尝试通过this.state.data[0]获取数据,则会有一个对象进入,那里有一个属性id

You are fetching your data from a remote source and this fetch operation is asynchronous. 您正在从远程源获取数据,并且此获取操作是异步的。 In the initial render of your app you don't have this data yet. 在您的应用最初渲染时,您还没有此数据。 componentDidMount triggers the fetch and your data lands in your app. componentDidMount触发获取操作,您的数据进入应用程序。 So, you should use a conditional rendering as recommended in the comments. 因此,您应该使用注释中建议的条件渲染。 Here is a simple example: 这是一个简单的示例:

 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> 

And with a little enhancement. 并进行了一些增强。 Because I'm pretty sure that you won't use a single data item in your app. 因为我很确定您不会在应用程序中使用单个数据项。 As a future reference, you can use this simple logic. 作为将来的参考,您可以使用这种简单的逻辑。 A better approach would be refactoring this code and writing a separate Post component. 更好的方法是重构此代码并编写一个单独的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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM