首页 > 解决方案 > 无法显示来自 API 的数据

问题描述

我有一些图表(用 Graph js 制作),我想在其中显示数据。

似乎我可以获取它们并且数据显示在制作中,但我无法在实际图表中显示它们。我尝试了不同的方法,甚至直接在返回字段中映射它,但它仍然没有工作并且显示它是未定义的。

const API = 'http://127.0.0.1:5000/models/';
const DEFAULT_QUERY = 'Vno';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: {},
            hits: [],
            isLoading: false,
            error: null
        };
    }

    getChartData() {
        const hits = this.state;
        const nextMonths = ['February', 'March', 'April', 'June', 'July', 'August', 'September', 'October'];

        this.setState({
            chartData: {
                labels: hits.pha,
                datasets: [
                    {
                        label: 'Dataset',
                        fill: false,
                        lineTension: 0.1,
                        backgroundColor: ['rgba(243, 129, 129, 0.4)', 'rgba(75,192,192,0.4)',
                            'rgba(249, 237, 105, 0.4)',
                            'rgba(184, 59, 94, 0.4)',
                            'rgba(106, 44, 112, 0.4)',
                            'rgba(0, 184, 169, 0.4)',
                            'rgba(135, 133, 162, 0.4)'],
                        borderColor: '#fae3d9',
                        borderCapStyle: 'butt',
                        borderDash: [],
                        borderDashOffset: 0.0,
                        borderJoinStyle: 'miter',
                        pointBorderColor: '#212121)',
                        pointBackgroundColor: '#252a34',
                        pointBorderWidth: 3,
                        pointHoverRadius: 5,
                        pointHoverBackgroundColor: 'rgba(75,192,192,1)',
                        pointHoverBorderColor: 'rgba(220,220,220,1)',
                        pointHoverBorderWidth: 2,
                        pointRadius: 5,
                        pointHitRadius: 10,
                        data: [50, 30, 40, 60]
                    }
                ],
            }
        })
    }

    componentDidMount() {
        this.setState({ isLoading: true });
        fetch(API + DEFAULT_QUERY)
            .then(response => {
                if (response.ok) {
                    return response.json();
                } else {
                    throw new Error('Something went wrong ...');
                }
            })
            .then(data => this.setState({ hits: data.hits, isLoading: false }))
            .catch(error => this.setState({ error, isLoading: false }));
    }

    componentWillMount() {
        this.getChartData();
    }

    render() {
        const { hits, isLoading, error } = this.state;
        if (error) {
            return <p>{error.message}</p>;
        }

        if (isLoading) {
            return <div className="react-spinner">
                <MDSpinner size={100} />
            </div>
        }
        return (
            <div className="App">
                <Navbar bg="light" variant="light">
                    <Navbar.Brand href="#">Aeroconseil</Navbar.Brand>
                    <Nav className="mr-auto">
                    </Nav>
                </Navbar>
                <hr className="hr-line"></hr>
                <div className="container">
                    <Chart chartData={this.state.chartData} />
                    <LineGraph chartData={this.state.chartData} />
                    <ul>
                        {hits.map(hit =>
                            <li key={hit.name}>
                                <a>{hit.pha}</a>
                            </li>
                        )}
                    </ul>
                </div>

            </div>
        );
    }
}

export default App;

我希望显示来自 API 的数据,但它显示未定义。

标签: javascriptreactjs

解决方案


可能有问题的几件事:

  1. 在你应该使用解构的定义的第一行getCharData,所以它应该是
getCharData() {
  const { hits } = this.state;
  // ...
}
  1. 生命周期方法在 React 16.3 中已componentWillMount弃用,并被替换为UNSAFE_componentWillMount,也许这就是你得到的原因undefined

  2. 在 React状态更新可能是异步的,所以你可以尝试使用componentDidUpdate生命周期方法

componentDidUpdate() {
  this.getCharData();
}

推荐阅读