第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

在React中調(diào)用API之前從html獲取數(shù)據(jù)屬性

在React中調(diào)用API之前從html獲取數(shù)據(jù)屬性

紫衣仙女 2021-04-16 15:15:21
我正在構(gòu)建一個(gè)React組件來(lái)加載博客文章以插入CMS中。我將從HTML的data-name屬性獲取作者姓名。當(dāng)我使用url2(作者的硬編碼名稱)運(yùn)行此代碼時(shí),一切正常。當(dāng)我使用url1(從數(shù)據(jù)屬性讀取的作者姓名)運(yùn)行代碼時(shí),沒(méi)有任何效果。請(qǐng)幫忙。我有這個(gè)HTML:<div id="dataElement" data-name="Peter Smith"></div>這是我的react組件中的代碼:constructor(props) {    super(props);    this.state = {       insightsData: [],      loading: true,      authorName: document.getElementById('dataElement').getAttribute('data-name').replace(/ /g, "_")    }  }  componentDidMount(){    let self = this;    let url2 = '/api/Insights/GetAuthorArticles?authorName=Peter_Smith&numRecords=5';    let url1 = `/api/Insights/GetAuthorArticles?authorName=${this.state.authorName}&numRecords=5`;    this.setState({loading:true});    var Promise = require("es6-promise");    Promise.polyfill();    axios.get(url)    .then((response) => {      self.setState({        insightsData: response.data.InsightsResults.Records      }, this.setState({loading:false}));      console.log(response.data.InsightsResults.Records);    });  }
查看完整描述

2 回答

?
呼喚遠(yuǎn)方

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超11個(gè)贊

html僅在構(gòu)造函數(shù)之后加載。使用react ref嘗試一下:


constructor(props) {

    super(props);

    this.state = { 

      insightsData: [],

      loading: true,

    }

  }


  componentDidMount(){

    let self = this;


    let url2 = '/api/Insights/GetAuthorArticles?authorName=Peter_Smith&numRecords=5';

    let url1 = `/api/Insights/GetAuthorArticles?authorName=${document.getElementById('dataElement').getAttribute('data-name').replace(/ /g, "_")}&numRecords=5`;


    this.setState({loading:true});

    var Promise = require("es6-promise");

    Promise.polyfill();

    axios.get(url)

    .then((response) => {

      self.setState({

        insightsData: response.data.InsightsResults.Records

      }, this.setState({loading:false}));

      console.log(response.data.InsightsResults.Records);

    });

  }


查看完整回答
反對(duì) 回復(fù) 2021-04-22
  • 2 回答
  • 0 關(guān)注
  • 243 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)