React Native:使用套接字io和mysql从数据库使用Flatlist显示数据

时间:2019-05-05 01:41:09

标签: mysql react-native socket.io

我想使用平面列表显示数据,但显示错误: 类型错误:未定义不是对象(评估'item.id.toString') 请帮我。 这是我的代码:

客户端:

      this.state = { chatMessages:[]};
      componentDidMount(){this.User()}

User = () =>{
    this.socket = io('http://192.168.43.172:3000')
    this.socket.on("readmsg", msg =>{
        this.setState({chatMessages: msg})
    })
}

ReadMsg = (item)=>{
     return(
            <View style={{flex:1}}>
                <Text>{item.pwd+' '+item.user}</Text>
            </View>
      );
}
    render() {
        return(
            <View style={{flex:1, justifyContent:'center'}}>
               <FlatList
                  data={this.state.chatMessages}
                  renderItem={({item}) => this.ReadMsg(item)}
                  keyExtractor={item => item.id.toString()}
              />
          </View>
        );
    }}

服务器:

const mysql    = require('mysql');
const express    = require('express');
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io").listen(server);
const port = 3000;

const con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "users"
});

io.on("connection", socket =>{
    console.log("a user is connected :D");
    con.query("SELECT * FROM user", function(err, rows){
        if(err) throw err;
        console.log(rows);
        socket.emit("readmsg", JSON.stringify(rows));
    })
})
server.listen(port, () => console.log("server running on port: "+port));

结果: enter image description here

0 个答案:

没有答案