我的程序无法正常运行,当我单击“添加播放器”按钮时,没有文档添加到mongo

时间:2018-11-29 05:12:15

标签: javascript reactjs mongodb meteor preventdefault

我想编写一个简单的程序在屏幕和mongodb上添加玩家名称,但是我是一个初学者,我想在流星中编写一个程序以将玩家添加到mongo,但是当我单击添加玩家按钮时,该程序无法正常工作,并且没有文档添加到mongo:

import './main.html';
import React from 'react';
import ReactDom from 'react-dom';
import {Meteor} from 'meteor/meteor'
import {Players} from './../imports/api/Players'
import {Tracker} from 'meteor/tracker'

const renderPlayers = (playersList) => {
   return playersList.map((player)=> {
        return <p key={player._id}>{player.name} has {player.score} point(s).</p>;
    });
};

const handleSubmit = (e) => {

    e.preventDefault();

    let playerName = e.target.playername.value;
    if (playerName){
        e.target.playerName.value = '';
        Players.insert ({
            name: playername,
            score: 0
        })
    }
}

Meteor.startup(() => {

    Tracker.autorun(() =>{
        let playersList = Players.find().fetch();
        let title = 'Score Keep';
        let name = 'Fateme';
        let jsx = (
            <div>
                <h1>{title}</h1>
                {renderPlayers(playersList)}
                <form name="New-Player" onSubmit={handleSubmit}>
                    <input type="text" name="PlayerName" placeholder="player Name"/>
                    <input type="submit" onClick={handleSubmit} value="add player"/>
                </form>
            </div>
        );
        ReactDom.render(jsx, document.getElementById('app'));
    });

});

1 个答案:

答案 0 :(得分:0)

在您的代码中e.target是指附加了onClicked处理程序的按钮。要引用输入字段值,您可以使用纯Javascript,也可以通过使用受控组件或非受控组件以React的方式进行操作。如果使用纯Javascript,请在​​输入标签中添加一个ID并以此为参考

await pool.query(query, binds, function (error, results) {
    if (error) throw error;
    res.send(JSON.stringify(results));
});

PlayerName将在文本框中包含该值。