相同的代码,但在localhost:3000和Internet(localhost:5000)的生产服务器上的行为不同

时间:2020-11-05 16:22:54

标签: javascript reactjs

我正在尝试学习React Js,但无法解决出现的错误:我的一个组件在本地服务器Localhost:3000上运行良好,但是相同的代码在生产服务器localhost:5000上显示了错误或在我的网域上。

TypeError: this.state.students.map is not a function
    at a.value (View.js:23)
    at a.value (View.js:42)
    at Vi (react-dom.production.min.js:187)
    at Bi (react-dom.production.min.js:186)
    at Wl (react-dom.production.min.js:269)
    at Ou (react-dom.production.min.js:250)
    at Cu (react-dom.production.min.js:250)
    at xu (react-dom.production.min.js:250)
    at vu (react-dom.production.min.js:243)
    at react-dom.production.min.js:123

这是我的代码:

import React, { Component } from 'react';
import Axios from 'axios';
import RecordsList from './RecordsList';

export default class View extends Component {

    constructor(props) {
        super(props);
        this.state = { students: [] };
    }

    componentDidMount() {
        Axios.get('http://pdp.1fortwo.com/php/list.php')
            .then(response => {
                this.setState({ students: response.data });
            })
            .catch(function (error) {
                console.log(error);
            })
    }

    usersList() {
        return this.state.students.map(function (object, i) {
            return <RecordsList obj={object} key={i} />;
        });
    }

    render() {
        return (
            <div>
                <h3 align="center">Users List</h3>
                <table className="table table-striped" style={{ marginTop: 20 }}>
                    <thead>
                        <tr>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Email</th>
                            <th colSpan="2">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        {this.usersList()}
                    </tbody>
                </table>
            </div>
        );
    }
}

3 个答案:

答案 0 :(得分:0)

原因是因为http://pdp.1fortwo.com/php/list.php返回一个空响应(如我所见,here),所以当您调用this.setState({ students: response.data });this.state.students.map处于不确定状态,因此无法映射结束。

您需要找出后端为何在生产中返回空响应的原因。

答案 1 :(得分:0)

map()是属于数组类型的一种方法,因此我猜您在另一台服务器上时从componentDidMount中的Axios.get获得的响应不会返回数组类型。

答案 2 :(得分:0)

我在DB中的数据是utf-8编码的,这似乎对我的PHP文件(list.php)中的json_encode函数有问题。当我向该函数添加选项JSON_UNESCAPED_UNICODE时,一切开始正常工作。

感谢您打算帮助我!

这是我的list.php文件:

$sql = "SELECT * FROM students";
//echo $sql;
$stmt = $conn->query($sql);

$cr=0;
$students = Array();
while($row = $stmt->fetch()) {
//    echo $row['sid'];
    $students[$cr]['sid'] = $row['sid'];
    $students[$cr]['fName'] = $row['fName'];
    $students[$cr]['lName'] = $row['lName'];
    $students[$cr]['email'] = $row['email'];
    $cr++;
}

echo json_encode($students, JSON_UNESCAPED_UNICODE);