反应this.props.id在类的一部分中未定义

时间:2019-04-03 10:14:04

标签: reactjs axios this state

在我的React应用程序中,我需要Timeline类中的userId来获取用户的帖子,但是React表示它是未定义的。

如果我在渲染部分说

{this.props.id}

然后它将显示正确的ID。

我已经尝试了所有可能在互联网上找到的解决方案。

import React, { Component } from 'react'
import axios from 'axios'
import Timeline from './Timeline'

class Profile extends Component{
    state = {
        user: {}
    }

    componentDidMount() {
        axios.get(`http://localhost:8090/user/${this.props.match.params.id}`)
          .then(res =>{
            const user = res.data
            this.setState({ user: user })
        })
    }

    render(){
    return(
        <div>
            <h1>This is the profile page of { this.state.user.username }.</h1>
            <img src={this.state.user.profilePicture} ></img>
            <h3> E-mailaddress: { this.state.user.mail }</h3>
            <Timeline id={this.state.user.id}/>
        </div>
    )}
}

export default Profile
import Cookies from 'universal-cookie'
import React, { Component } from 'react'
import axios from 'axios'

const cookies = new Cookies()

class Timeline extends Component {

  state = {
    user: cookies.get('user'),
    posts: []
  }

  componentDidMount() {
    const id = this.props.id
    console.log("ID IS " + id)
    if (this.state.user === undefined)
      return



    axios.get(`http://localhost:8090/user/${id}/postEntities`)
    .then(response => {
      this.setState({
        posts: response.data._embedded.post
      })
    })
    .catch(error => {
      console.log(error)
    })
  }

  render() {
    if (this.state.user !== undefined) {
      if (this.state.posts.length <= 0) {
        return (
          <main>
            <h2>Personal timeline</h2>
            <h2>This id works: { this.props.id }</h2>
            <h6>There does not seem to be anything here..<br />Create a post and come back later!</h6>
          </main>
        )
      } else {
        return (
          <main>
            <h2>Personal timeline</h2>
            {
              this.state.posts.map(post => {
                return (
                  <div>
                    <h5>{ post.title }</h5>
                    <img src={post.pictureUrl} width="200" height="200"></img>
                    <p><i>You took this picture at { post.longitude }, { post.latitude }</i></p>
                  </div>
                )
              })
            }
          </main>
        )
      }
    }
    else {
      return (
        <h5>You need to be logged in to use this feature</h5>
      )
    }
  }
}

export default Timeline

URL中的预期输出需要为2,但未定义,呈现部分的预期值为2,并且输出为2。

4 个答案:

答案 0 :(得分:1)

因为

  

this.state.user.id

仅在componentDidMount中的axios.get函数完成后才有价值。而函数render()之前已被调用。

因此,为了避免未定义,您必须使用以下格式设置状态:

state = {
    user: {id : 0} //or null
}

答案 1 :(得分:1)

通过react,子级组件的componentDidMount在父级组件之前被称为。

因此,当第一次调用时间轴的componentDidMount时,尚未调用Profile的componentDidMount,因此还没有userId。

为避免此问题,只有在安装了Profile组件并具有用户ID时,才应渲染时间轴。

在个人资料的渲染中类似

render(){
return(
    <div>
        <h1>This is the profile page of { this.state.user.username }.</h1>
        <img src={this.state.user.profilePicture} ></img>
        <h3> E-mailaddress: { this.state.user.mail }</h3>
        {this.state.user.id && (
            <Timeline id={this.state.user.id}/>
        )}
    </div>
)}

答案 2 :(得分:0)

最初,您没有user.id,它来自axios服务调用。在这种情况下,请等到收到响应后再根据渲染条件显示时间轴。

instance = Series(**d)
# The ** is called dictionary unpacking which you can google if you need.
# If an attribute value doesn't exist in the dictionary, it will be None by
# default.
session.add(instance)
session.commit()

答案 3 :(得分:0)

未定义什么变量? this.state.user.id?

如果是这样,则可能意味着您以user: {}开始,然后您做出了承诺,然后设置了状态。问题在于,兑现承诺要花费一些时间,所以与此同时,您仍然user: {}this.state.user.id给出了未定义的内容。

致电<Timeline id={this.state.user.id}/>时,请确保您的身份和电子邮件处于您的状态。或使用user: {is: '', email:''}定义状态或进行条件渲染。希望我能正确理解您的问题!