ReactjS-const在获取之前加载所有状态

ReactjS-const在获取之前加载所有状态,reactjs,Reactjs,嘿,伙计们,我正在尝试将背景图像的URL传递到ResultsItem组件中。我的问题是,在获取数据之前,不会定义位置的状态。问题在于常量缩略图。我总是得到一个错误“TypeError:无法读取未定义的属性'photos' render(){ 常量缩略图=`https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=${places.photos.photoreference}&key=MYAPIKEY

嘿,伙计们,我正在尝试将背景图像的URL传递到ResultsItem组件中。我的问题是,在获取数据之前,不会定义位置的状态。问题在于常量缩略图。我总是得到一个错误“TypeError:无法读取未定义的属性'photos'

render(){
常量缩略图=`https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=${places.photos.photoreference}&key=MYAPIKEY
`;
返回(
{this.state.lat}&{this.state.lng}
{this.state.places.map(places=>(
))}
);
}
}

事实上,places是以异步方式提供的,最好的解决方案是在map函数本身中解析缩略图

这样,只有在有空位时才需要解决

render() {

    return (
      <div>
        <div className="flex align-center">
          <div className="search">
            <SearchInput
              id="autocomplete"
              placeholder="Search by address"
              width="100%"
              height={56}
            />
            <Script
              url="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&libraries=places,geometry&callback=initAutocomplete"
              onLoad={this.handleScriptLoad}
            />
          </div>
          <div className="current-location">
            <Tooltip content="Use current location">
              <IconButton
                icon="locate"
                iconSize={16}
                height={32}
                onClick={this.currentLocationOnClick}
              >
                {this.state.lat} & {this.state.lng}
              </IconButton>
            </Tooltip>
          </div>
        </div>

        <div className="results">
          {this.state.places.map(places => {
           const Thumbnail = `https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=${places.photos.photoreference}&key=MYAPIKEY
    `;
           return(
            <div className="results-item" onClick={this.props.sideBarOpen}>
              <ResultsItem name={places.name} image={Thumbnail} />
            </div>
          )})}
        </div>
      </div>
    );
  }
}
render(){
返回(
{this.state.lat}&{this.state.lng}
{this.state.places.map(places=>{
常量缩略图=`https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=${places.photos.photoreference}&key=MYAPIKEY
`;
返回(
)})}
);
}
}

您应该防止在从服务器实际加载数据之前加载数据,因此您应该在使用结果之前呈现加载程序,方法如下:

if(isLoading) { // You should set the loading state before to load data from server
  return <span>Loading</span>
}
return ( // This shows your data after loading goes to false
  <div>Your code here</div>
)
if(isLoading){//您应该在从服务器加载数据之前设置加载状态
回装
}
return(//这显示加载后的数据为false
你的代码在这里
)

好人,谢谢!这帮了大忙。同样感谢您的提示回答,您可以简单地保护渲染部分-“条件渲染”<代码>{this.state.places&&
if(isLoading) { // You should set the loading state before to load data from server
  return <span>Loading</span>
}
return ( // This shows your data after loading goes to false
  <div>Your code here</div>
)