猿问

在React中调用API之前从html获取数据属性

我正在构建一个React组件来加载博客文章以插入CMS中。我将从HTML的data-name属性获取作者姓名。当我使用url2(作者的硬编码名称)运行此代码时,一切正常。当我使用url1(从数据属性读取的作者姓名)运行代码时,没有任何效果。请帮忙。


我有这个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);

    });

  }


紫衣仙女
浏览 226回答 2
2回答

呼唤远方

html仅在构造函数之后加载。使用react ref尝试一下:constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {&nbsp;&nbsp; &nbsp; &nbsp; insightsData: [],&nbsp; &nbsp; &nbsp; loading: true,&nbsp; &nbsp; }&nbsp; }&nbsp; componentDidMount(){&nbsp; &nbsp; let self = this;&nbsp; &nbsp; let url2 = '/api/Insights/GetAuthorArticles?authorName=Peter_Smith&numRecords=5';&nbsp; &nbsp; let url1 = `/api/Insights/GetAuthorArticles?authorName=${document.getElementById('dataElement').getAttribute('data-name').replace(/ /g, "_")}&numRecords=5`;&nbsp; &nbsp; this.setState({loading:true});&nbsp; &nbsp; var Promise = require("es6-promise");&nbsp; &nbsp; Promise.polyfill();&nbsp; &nbsp; axios.get(url)&nbsp; &nbsp; .then((response) => {&nbsp; &nbsp; &nbsp; self.setState({&nbsp; &nbsp; &nbsp; &nbsp; insightsData: response.data.InsightsResults.Records&nbsp; &nbsp; &nbsp; }, this.setState({loading:false}));&nbsp; &nbsp; &nbsp; console.log(response.data.InsightsResults.Records);&nbsp; &nbsp; });&nbsp; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答