Ошибка типа: не удается прочитать свойство 'profile_image_url' из неопределенного - PullRequest
0 голосов
/ 02 октября 2018

У меня есть следующий объект и я пытаюсь получить доступ к его свойствам.

Однако я получаю сообщение об ошибке.

Вот мой код:

export default class TweetsList extends Component {
state={
    tweet:''
}
componentDidMount(){
    var tweet_id  = window.location.search.split("id=")[1];
    console.log(tweet_id, 'tweet id');
    axios.request({
        method: 'POST',
        url: 'http://localhost:4444/fetchSingleTweet', 
        data:{
            tweet_id: tweet_id,
            token: localStorage.getItem('token')
        },
    }).then((res)=>{  
        this.setState({tweet:res.data});     
    }).catch((err)=>{
        this.setState({isLoading:false});
    });
}
render(){
    let tweet = this.state.tweet;
    console.log(JSON.stringify(tweet.user))
    return(
      <div class="card">

          </div>
      )
}

}

Я могу получить доступ к tweet.user, но не к tweet.user.id или любому из user свойств внутри render функции.

Я утешил объект, и он выглядит так:

{
created_at: "Tue Oct 02 09:06:45 +0000 2018", id: 1047050242053627900, 

id_str: "1047050242053627904", text: "RT @CharlesPPierce: When Worlds Collide.↵Over the …I learned that the guy who cut Brett Kavanaugh f…", truncated: false, …}

created_at: "Tue Oct 02 09:06:45 +0000 2018"
entities: {hashtags: Array(0), symbols: Array(0), user_mentions: Array(1), urls: Array(0)}
favorite_count: 0
favorited: true
geo: null
id: 1047050242053627900
id_str: "1047050242053627904"
in_reply_to_screen_name: null
in_reply_to_status_id: null
in_reply_to_status_id_str: null
in_reply_to_user_id: null
in_reply_to_user_id_str: null
is_quote_status: false
lang: "en"
place: null
retweet_count: 28
retweeted: false
retweeted_status: {created_at: "Mon Oct 01 12:19:08 +0000 2018", id: 1046736268418256900, id_str: "1046736268418256896", text: "When Worlds Collide.↵Over the weekend, thanks to Y…uy who cut Brett Kavanau…", truncated: true, …}
source: "<a href="" rel="nofollow">Twitter for iPad</a>"
text: "RT @CharlesPPierce: When Worlds Collide.↵Over the weekend, thanks to Yahoo!'s Pete Thamel, I learned that the guy who cut Brett Kavanaugh f…"
truncated: false
user: {id: 938841256507183100, id_str: "938841256507183105", name: "Irene Kenneth", screen_name: "IreneKenneth3", location: "", …}
__proto__: Object

Кроме того, вот расширенное представление свойства user:

    {
  "id": 736476636015530000,
  "id_str": "736476636015529987",
  "name": "NepalaYak",
  "screen_name": "NepalaYak",
  "location": "Kathmandu, Nepal",
  "description": "Treks & Tours Company. Let's discover #Nepal with #Nepalayak",
  "url": "some_url",
  "entities": {
    "url": {
      "urls": [
        {
          "url": "some_urlr",
          "expanded_url": "http://nepalayak.com/",
          "display_url": "nepalayak.com",
          "indices": [
            0,
            23
          ]
        }
      ]
    },
    "description": {
      "urls": []
    }
  },
  "protected": false,
  "followers_count": 198,
  "friends_count": 95,
  "listed_count": 3,
  "created_at": "Sat May 28 08:38:07 +0000 2016",
  "favourites_count": 40,
  "utc_offset": null,
  "time_zone": null,
  "geo_enabled": false,
  "verified": false,
  "statuses_count": 368,
  "lang": "en",
  "contributors_enabled": false,
  "is_translator": false,
  "is_translation_enabled": false,
  "profile_background_color": "000000",
  "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
  "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
  "profile_background_tile": false,
  "profile_image_url": "http://pbs.twimg.com/profile_images/907526265627971584/T8gahYIg_normal.jpg",
  "profile_image_url_https": "https://pbs.twimg.com/profile_images/907526265627971584/T8gahYIg_normal.jpg",
  "profile_banner_url": "https://pbs.twimg.com/profile_banners/736476636015529987/1524287352",
  "profile_link_color": "9B0103",
  "profile_sidebar_border_color": "000000",
  "profile_sidebar_fill_color": "000000",
  "profile_text_color": "000000",
  "profile_use_background_image": false,
  "has_extended_profile": false,
  "default_profile": false,
  "default_profile_image": false,
  "following": false,
  "follow_request_sent": false,
  "notifications": false,
  "translator_type": "none"
}

В чем причина этой ошибки, я не уверен.

Как я могу получить доступ к свойствам объекта?

1 Ответ

0 голосов
/ 02 октября 2018

Вы можете использовать object.item, обратите внимание, что в первом примере он находится внутри массива, поэтому вы должны указать первый массив с помощью obj[0], а затем использовать obj[0].item точечную нотацию.

Чтобы я дал вам точното, что вы ищете, вам необходимо скопировать полный объект JSON с начала скобок { }.или начало и конец массива [].Этот не действителен, если вы не скопировали полностью.Вы можете использовать JSON beautifier для более удобного просмотра дерева.

Если у вашего объекта есть «элемент», вы используете obj.item (точечная запись), в противном случае используйте obj["item"]. Обратите внимание на кавычки.

var obj = [
      {
      "one": "1",
      "two": "2",
      "nested": {
         "nested-one": "nested-1"
      }
    }]
    var obj2 = {
      "example_two": "example-2"
    }
    
var yours = {
  item: {
     name: "example"
  }
}
    console.log(obj[0].one)
    console.log(obj2.example_two)
    
    // Your case
    console.log(yours['item'].name)
    

Итак, вы берете эти цены в свой объект JSON и затем используете {obj.entry['item']}

...