如何获取变量并将其用作反应中的道具?

问题描述

我正在尝试将值传递给我的react应用程序中的组件。该值位于函数内部,当我尝试将其呈现为react组件中的prop时,该值未定义。如何正确访问此变量? P.S变量是tableSiteId;通常,构建这些组件的最佳实践是什么?

async getSiteInfo(companyId,companyName,divisions,userId,userType){
  var userinv = []
  for(let key in this.state.userInventory){
    userinv.push(this.state.userInventory[key])
  }
  var inv=userinv[2]
  var fullUserInv = []
  var userInvArr=[]
  
await Promise.all(
      inv.map(async key => {
        return fetch(backendUrl +'/getsiteinfo',{
          method: "POST",headers: {
            'Accept': 'application/json','Content-Type': 'application/json'
          },//make sure to serialize your JSON body
          body: JSON.stringify({
            site_id:key.site_id
        })
        
      })
        .then(res => res.json())
        //Uncomment below to view the response as a console log. Note,the data will not be pulled into the table if you do this//
        // .then(response=>console.log(response))
    /* THIS NEEDS TO BE FIXED,SOME USERS CANNOT GET ALL OF THEIR DATA BECAUSE THEIR ORGS DO NOT CONTAIN DIVERSITY OR GEOGRAPHY */
        .then(data1 =>{ 
          var diversities = '';
          var geo = '';
          var location = '';
          var site_id = '';
          if(data1.site_metadata) location = data1.site_metadata.company_state_full;
          if(data1.site_metadata) site_id = data1.site_metadata.site_id;
          if(data1.diversities) diversities = data1.diversities[0].diversity;
          // if(data1.locations) geo = data1.locations[0].geography;
          userInvArr.push([data1.site_metadata.site_name,"N/A",diversities,location,`<div class="btn-group" role="group" aria-label="Basic example"><button type="button" data-toggle="modal" data-target="#notes-modal" data-site_id="${site_id}" class="btn btn-primary add-notes-btn">Create</button><button type="button" data-site_id="${site_id}" class="btn btn-primary view-notes-btn">View</button></div>`
        
        ])
        })
        // `<button class="button primary notes-btn" data-site_id="${site_id}">Notes</button>`
    .then(()=>{
        this.setState({
            inventoryNewData:userInvArr,fullUserInventory:fullUserInv,viewUserInventory:true
        })
          })
          .then(()=>{
  //function for generating the user table before datatables plugin styles it//

        CreateUserTable(userInvArr)

  //---------------------------------------------------------------------------------//

                //---------------DATATABLES PLUGIN-------------------//

        var row_count = $('#user-table-body tr').length;
        this.setState({
          counter:row_count
        })
        let table = $('#user-table-body').DataTable(
          {
            dom: "<'row'<'col-sm-12'tr>>" +
            "<'row'<'col-sm-4'l><'col-sm-8'p>>","pageLength": 15,lengthMenu: [ 1,5,10,15,20],language: {searchPlaceholder: "Search Organizations and Contacts",search: "",paginate: {
            'next': '<i class="icon-angle-right"></i>','previous': '<i class="icon-angle-left"></i>'
    },sLengthMenu: " _MENU_" }
     
    
        });  
        $('#ofccp-search-keyword1').keyup(function(){
          table.search($(this).val()).draw()
    })
        $('#ofccp-search-keyword2').on('change',function(){
          table.columns(2).search($(this).val()).draw(); //Exact value,column,reg
        });
    
        $('#ofccp-search-keyword3').keyup(function(){
          table.columns(3).search($(this).val()).draw();
    })
  })
}))

//-----------------------------------------------CREATE BUTTON TO NAVIGATE TO ADD ORG PAGE---------------------------------------------------------//
this.createButton()

//-------------------------------------------------------------------------------------------------------------//

                  //-------------------------NOTES LOGIC FOR CREATING AND VIEWING-----------------------------------//


         

//declare tableSiteId variable//
  var tableSiteId;
//----------Initializing tableSiteId variable------------//                  
$('.add-notes-btn').on( 'click',function noteTitle (e) {
     tableSiteId= $(this).data("site_id")
       
    })

     //------First onclick is for creating the note and storing in mongoDB---//
    $('.submit-note').on( 'click',function (e) {
      // $('#modalName').val(tableOrgName)
      fetch(backendUrl +'/notes',{
      method: "POST",headers: {
        'Accept': 'application/json','Content-Type': 'application/json'
      },//make sure to serialize your JSON body
      body: JSON.stringify({
        user_id:userId,content:$("#message-text").val(),site_id:parseInt(tableSiteId),company_id:parseInt(companyId),company_name:companyName,divisions:parseInt(divisions),user_type:userType
        
    })
    
  })
    .then(res => res.json())
    .then(data=>console.log(data))
  })

//----------Second onclick is for viewing the notes based on company ID and site ID--------------//

$('.view-notes-btn').on( 'click',function (e) {
    let tableSiteId= $(this).data("site_id")
    fetch(backendUrl +'/getnotes',{
        method: "POST",headers: {
          'Accept': 'application/json','Content-Type': 'application/json'
        },body: JSON.stringify({
        user_id:userId,user_type:userType
        
    })
    })  
    .then(res => res.json())
    .then(data=>console.log(data))
  })
}
 <div class="modal fade" id="notes-modal" tabindex="-1" role="dialog" aria-labelledby="notes-modal" aria-hidden="true">    
 <div className="modal-dialog" role="document">
      <div className="modal-content">
        <div className="modal-header">
          <h5 className="modal-header-description" id="exampleModalLongTitle">Add New Note</h5>
          <button type="button" className="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
          <CreateNote tableSiteId={this.tableSiteId}/>
      </div>
    </div>
  </div>
            <div id='header'></div>
            <section className="outer-container">
                <div className="container container-wrapper">
                  <div className="row">
            
                  <div className="col-md-12">
                    <div className="header-group">
                        <h2 id="page-title" className="page-title"><img src={Logo} className='logo' />OFCCP Local Outreach</h2>
                    </div>
                </div> 

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...