繁体   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