如何在JS / React外部访问嵌套函数?

时间:2017-04-08 20:55:17

标签: javascript function reactjs scope closures

我在使用范围函数方面遇到了一些麻烦。我试图获取“item”的值,但是当我尝试在函数外部访问它时,我得到了未定义。如何从外部onLinkClicked()访问“item”?我需要能够在渲染中使用项目。

   onLinkClicked() {

   var parent = this.state.username
       //console.log(this.state.username)
   var conn = new jsforce.Connection({
       serverUrl: 'https://cs63.salesforce.com',
       accessToken: sessionStorage.getItem('token')
   })
   conn.query("SELECT Id, Name, Phone FROM Contact WHERE LastName='" + parent + "'",
       function(err, result) {
           if (err) {
               return console.error(err);
           }

             var a = result
              a.records.forEach(function(item) {
               result = (item.Name + ' ' + item.Phone);

               console.log(item) // I'm trying to get the value of item, which outputs correctly here

           });

       }
   )

   console.log(item) //Here I get undefined due to being out of scope, how can I access item?.

  }

 render () {

return (
    <div className='menubox' id='menubox'>
  <div className='searchbar-container'>
    <form onSubmit={e => e.preventDefault()}>
      <input
        type='text'
        size='25'
        placeholder='Contact Last Name'
        onChange={this.handleChange.bind(this)}
        value={this.state.username} />
        <button
        type='submit'
        onClick={this.onLinkClicked.bind(this)}>
        Search
      </button>
    </form>
   </div>
   <div dangerouslySetInnerHTML={ { __html: item } }>
   </div>
  </div>

 )
}

1 个答案:

答案 0 :(得分:1)

定义存储结果的全局变量。如果您正在使用react(您正在使用的反应类没有完全显示),您应该使用this.setState来设置状态并在其他地方使用它。 conn.query-method之后不能使用item,因为conn.query是异步的。如果你想在回调中用它来处理它。

我假设你需要渲染函数中的项目。随着国家这很容易实现。

请注意,我将function - 定义更改为lambda表达式(() => {})。为了在回调中使用this,这是必要的。

... () {
  // ...
  conn.query("SELECT Id, Name, Phone FROM Contact WHERE LastName='" + parent + "'",
           (err, result) => {
             if (err) {
               return console.error(err);
             }

             var a = result;
             a.records.forEach((item) => {
               result = (item.Name + ' ' + item.Phone);
               this.setState({item : item});
             });

           };
          );

  // You will never be able to get item here, because you are using an
  // asynchronous function. If you want to use item further in this
  // function you have to use it within the callback of conn.query.
  console.log(item);
};

render () {
  // Nevertheless you can use this.state.item here. I assume this is
  // what you want.
  return ( // ...
  );
}