如何在从API中获取数据后重新呈现表格 - React

时间:2018-04-24 15:36:14

标签: c# reactjs

我正在使用react-bootstrap-table来呈现表格。我从API获取信息,然后我希望表重新渲染。我很反应,并且很清楚在哪里设置数据的状态,以便我的表在接收数据后正确呈现。如果我直接在渲染中设置数据(而不是从API),这会呈现实际信息,因此它不是表格设置。

以下是我到目前为止的情况。我尝试过几个不同的地方,所以如果完全错了,请耐心等待。

import React, { Component } from 'react';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import 'react-bootstrap-table-next/dist/react-bootstrap-table2.min.css';
import $ from 'jquery'; 

class Table extends Component {
    constructor(props) {
        super(props);
        //Controlled Component


        this.state = {
            poData: []
        };
    }

    componentDidMount() {
        var pos = [];

        function myCallBack(data) {
            // place your code here to do the work
            var obj = JSON.parse(data);

            // sample processing debug statements
            var s = 'retrieved this data from suitelet: ';
            console.log(s + data);
            //alert(s + data);
            return obj;
        }

        function getPOs() {
            var obj2 = [];
            alert("hi");
            // name of the call back function that drives the JSONP mechanism; this string must be the same
            // as your function that will ultimately process your request.
            var cb = 'myCallBack'

            //produce the JSON payload; JQuery will automatically add it to the URL for a JSONP call.
            var data = { id: '24567', user: '23455' };

            //note JQuery wants to see "callback=?" at the end of the URL; it tells the .getJSON call that this JSON request is of type JSONP
            var url = 'https://myapi.com&callback=?';

            //finally, the call. For convenience, we sent the data to our custom myCallBack function -- yet not mandatory in this implementation; the call back is in
            // already referenced via the .done() method. Other JQuery capacities are can take care of failed calls

            $.getJSON(url, data)
                .done(function (data) {
                    obj2 = myCallBack(data);
                })

            return obj2;
        }

        var obj2 = getPOs();
        this.setState({ poData: obj2 });
    }

    componentWillUnmount() {
        this.setState({ poData: [] });
    }



    render() {

        var poData = this.state.poData;

        return (
            <div>  
                <BootstrapTable data={poData} className="table" version='4'>
                    <TableHeaderColumn dataField='poID' isKey>PO ID</TableHeaderColumn>
                    <TableHeaderColumn dataField='poName'>PO Name</TableHeaderColumn>
                    <TableHeaderColumn dataField='poShipDate'>PO Ship Date</TableHeaderColumn>
                </BootstrapTable>
            </div>
        );
    }
}

export default Table;

编辑:

好的,我已经清理了一些。我尝试了下面提到的componentDidMount,但我的数据永远不会更新。

我现在所拥有的内容实际上会正确地改变状态,但它实际上仍然没有实际更新表格。有什么想法吗?

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Login from './Components/Login';
import Table from './Components/Table';
import $ from 'jquery'; 

class App extends Component {
    constructor(props) {
        super(props)
        // the initial application state
        this.state = {
            isLoggedIn: false,
            username: '',
            password: '',
            poData: []
        };
    }

    componentDidMount() {
        //TODO
    }

    signIn(username, password) {
        // This is where you would call Firebase, an API etc...
        // calling setState will re-render the entire app (efficiently!)
        this.setState(
            {
                username: username,
                password: password,
                isLoggedIn: true,
                poData: []
            }
        )
    }

    updateTable(poData) {
        this.setState({
            poData: poData
        });
    }

    render() {
        // Here we pass relevant state to our child components
        // as props. Note that functions are passed using `bind` to
        // make sure we keep our scope to App
        return (
                <div>
                {
                    (this.state.isLoggedIn) ?
                        <div>
                            <Table data={this.state.poData} onUpdate={this.updateTable.bind(this)} />
                        </div>
                        :
                        <div>
                            <Login onSignIn={this.signIn.bind(this)} />
                        </div>
                }
            </div>
        )
    }
}

export default App;

和Table.js

import React, { Component } from 'react';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import 'react-bootstrap-table-next/dist/react-bootstrap-table2.min.css';
import $ from 'jquery'; 
import App from '../App';

class Table extends Component {
    constructor(props) {
        super(props);

        this.state = {
            poData: []
        };

        this.getPOs = this.getPOs.bind(this);
    }

    getPOs() {

        var url = 'https://myapi.com';

        //CORS URL so that we can ignore the stupid CORS stuff
        var proxyURL = 'https://cryptic-headland-94862.herokuapp.com/';

        fetch(proxyURL + url).then(response => response.json().then(data => {
            console.log(data);
            console.log(data.length);
            this.props.onUpdateTable(data);
        }));
    }

    componentDidMount() {
        //this.getPOs();        
    }

    componentWillUnmount() {
        //this.setState({ poData: [] });
    }

    render() {

        this.getPOs();

        return (
            <div>
                <BootstrapTable data={this.state.poData} className="table" version='4'>
                    <TableHeaderColumn dataField='poID' isKey>PO ID</TableHeaderColumn>
                    <TableHeaderColumn dataField='poName'>PO Name</TableHeaderColumn>
                    <TableHeaderColumn dataField='poShipDate'>PO Ship Date</TableHeaderColumn>
                </BootstrapTable>
            </div>
        );
    }
}

export default Table;

1 个答案:

答案 0 :(得分:1)

您应该制作获取请求并将结果存储在state的{​​{1}}中。获取后需要ComponentDidMount(),然后将数据传递给done()