簡體   English   中英

在渲染之前等待 react-promise 解決

[英]Wait for react-promise to resolve before render

因此,我有大量數據是從 API 中檢索的。 我認為問題在於我的組件在從承諾接收數據之前調用了 renderMarkers 函數。

所以我想知道如何在調用我的 renderMarkers 函數之前等待完全解析數據的承諾?

class Map extends Component {

componentDidMount() {
  console.log(this.props)
  new google.maps.Map(this.refs.map, {
    zoom: 12,
    center: {
      lat: this.props.route.lat,
      lng: this.props.route.lng
    }
  })
}

componentWillMount() {
  this.props.fetchWells()
}

renderMarkers() {
  return this.props.wells.map((wells) => {
    console.log(wells)
  })
}

render() {
  return (
    <div id="map" ref="map">
      {this.renderMarkers()}
    </div>
  )
 }
} 

function mapStateToProps(state) {
  return { wells: state.wells.all };
}

export default connect(mapStateToProps, { fetchWells })(Map);

你可以做這樣的事情來顯示一個加載器,直到所有的信息都被獲取:

class Map extends Component {
  constructor () {
    super()
    this.state = { wells: [] }
  }

  componentDidMount() {
    this.props.fetchWells()
      .then(res => this.setState({ wells: res.wells }) )
  }

  render () {
    const { wells } = this.state
    return wells.length ? this.renderWells() : (
      <span>Loading wells...</span>
    )
  }
}

對於帶鈎子的功能組件:

    function App() {
        
          const [nodes, setNodes] = useState({});
          const [isLoading, setLoading] = useState(true);
        
          useEffect(() => {
            getAllNodes();
          }, []);
        
          const getAllNodes = () => {
            axios.get("http://localhost:5001/").then((response) => {
              setNodes(response.data);
              setLoading(false);
            });
          };
        
        
          if (isLoading) {
            return <div className="App">Loading...</div>;
          }
          return (
            <>
              <Container allNodes={nodes} />
            </>
        
          );
}

在 API 調用完成之前調用渲染函數是可以的。 wells是一個空數組(初始狀態),你什么都不渲染。 並且在從 API 接收到數據后,您的組件將自動重新渲染,因為道具(redux store)的更新。 所以我沒有看到問題。

如果你真的想阻止它在接收 API 數據之前渲染,只需在你的渲染函數中檢查一下,例如:

if (this.props.wells.length === 0) {
  return null
}

return (
  <div id="map" ref="map">
    {this.renderMarkers()}
  </div>
)

所以我有類似的問題,我自己做出反應並找到了解決方案。 通過使用 Async/Await 調用 react 下面的代碼片段請試試這個。

 import Loader from 'react-loader-spinner'

 constructor(props){
    super(props);
    this.state = {loading : true}
  }
  getdata = async (data) => {
    return await data; 
  }
  getprops  = async (data) =>{
    if (await this.getdata(data)){
      this.setState({loading: false})
    }
  }
  render() {
  var { userInfo , userData} = this.props;
    if(this.state.loading == true){
      this.getprops(this.props.userData);
    } 
    else{
//perform action after getting value in props
    }
    return (
      <div>
      {
           this.state.loading ? 
             <Loader
               type="Puff"
               color="#00BFFF"
               height={100}
               width={100}
             />
           :    
              <MyCustomComponent/> // place your react component here
      }
      </div>
      )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM