React-呈现了ajax返回的数据后,调用javascript函数

时间:2018-08-18 16:25:20

标签: reactjs

我有以下数据加载器组件在反应。它从API端点获取数据,并使用该数据呈现HTML。

import React, { Component } from "react";
import PropTypes from "prop-types";
class DataLoader extends Component {

          static propTypes = {
             endpoint: PropTypes.string.isRequired,
             render: PropTypes.func.isRequired,
             callback: PropTypes.func
          };

          state = {
             data: [],
             loaded: false,
             placeholder: "Loading..."
          };

        componentDidMount() 
        {
             fetch(this.props.endpoint)
               .then(response => {
                   if (response.status !== 200) {
                   return this.setState({ placeholder: "error" });
               }

               return response.json();
             })
            .then(data => this.setState({ data: data, loaded: true } ))
            .then(  this.props.callback );
       }

       render() {
           const { data, loaded, placeholder } = this.state;
           return loaded ? this.props.render(data) : <p>{placeholder}</p>;
       }
}

export default DataLoader;

这是App.jsx文件

import React from "react";
import ReactDOM from "react-dom";
import DataLoader from "./DataLoader"; 
import EventDivs from "./EventDivs";


 const App = () => (
     <DataLoader endpoint="api/v1/calendarevents/" 
               render={data => <EventDivs data={data} />}
               callback = {function() {
                   console.log($("#renderedDiv").length);
               }} 
     />
 );


const appid = document.getElementById("app");
appid ? ReactDOM.render(<App />, appid ) : null;

console.log($("#renderedDiv").length)获得0,因为this.props.callbackfetch的回调。

我想知道在呈现Ajax返回的数据之后如何调用该函数吗?

0 个答案:

没有答案