Javascript localhost:3000和Internet上的生产服务器(localhost:5000)上的代码相同,但行为不同
我正在尝试学习React Js,但我无法解决我遇到的错误:我的一个组件在本地服务器Localhost:3000上运行良好,但相同的代码在生产服务器Localhost:5000或Internet上的我的域上显示错误Javascript localhost:3000和Internet上的生产服务器(localhost:5000)上的代码相同,但行为不同,javascript,reactjs,Javascript,Reactjs,我正在尝试学习React Js,但我无法解决我遇到的错误:我的一个组件在本地服务器Localhost:3000上运行良好,但相同的代码在生产服务器Localhost:5000或Internet上的我的域上显示错误 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.mi
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>
);
}
}
import React,{Component}来自'React';
从“Axios”导入Axios;
从“/RecordsList”导入RecordsList;
导出默认类视图扩展组件{
建造师(道具){
超级(道具);
this.state={students:[]};
}
componentDidMount(){
Axios.get()http://pdp.1fortwo.com/php/list.php')
。然后(响应=>{
this.setState({students:response.data});
})
.catch(函数(错误){
console.log(错误);
})
}
用户列表(){
返回this.state.students.map(函数(对象,i){
返回;
});
}
render(){
返回(
用户列表
名字
姓
电子邮件
行动
{this.usersList()}
);
}
}
原因是http://pdp.1fortwo.com/php/list.php
返回一个空响应(如我所见),因此当调用this.setState({students:response.data})时
此.state.students.map未定义,因此无法映射
您需要找出后端在生产时返回空响应的原因。map()是属于数组类型的方法,因此我猜测您从Axios获得的响应。当您在另一台服务器上时,get-in componentDidMount不会返回数组类型。我的数据库中的数据是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);