var 不能在函数中设置,但会丢失函数外的值。var 不应该全局可用来设置 [duplicate]

var cannot be set in function but looses value outside of function. Shouldn't var be available globally to set [duplicate]

提问人:Pasang 提问时间:11/11/2023 最后编辑:Pasang 更新时间:11/11/2023 访问量:35

问:

我有一个 MUI 自动完成组件。我正在尝试通过声明 var zipCode 来设置 zipCode,但是在调用通过调用 getZipCode 函数设置 zipCode 的 getGeocode 函数后,zipCode 在 getGeocode 函数中保留了值,但是当 return 语句返回组件时,zipCode 再次为空。<li>

在getGeocode中没有设置var Zipcode是因为我正在使用promises吗?

<Autocomplete        
        renderOption={(props, option) => {
          var zipCode='';          
          getGeocode({placeId: option.place_id}).then(results => {
            zipCode = getZipCode(results[0], true);  // zipcode gets assigned here          
          });          
          return (
            <li {...props} >             
                 {`${zipCode}`}                       // zipcode is empty again
            </li>
          )
        }
        }
      />    
JavaScript 承诺 变量

评论


答: 暂无答案