【问题标题】:Option tag not inserting values in MongoDB using React and NodeJS选项标签未使用 React 和 NodeJS 在 MongoDB 中插入值
【发布时间】:2020-08-16 04:00:06
【问题描述】:

我正在尝试使用 MERN 插入选项值标签,但是每当我尝试在数据库中插入时,它什么也没插入,我似乎找不到问题所在。我刚开始学习MERN。无论如何,这是我写的代码。任何帮助将不胜感激。提前致谢:)

export default class AddClient extends Component {
  constructor(props) {
    super(props);
    this.onChangeExisting = this.onChangeExisting.bind(this);
    this.onSubmit = this.onSubmit.bind(this);

    this.state = {
      existing: "",
    };
  }

  onChangeExisting(e) {
    this.setState({
      existing: e.target.value,
    });
  }


  onSubmit(e) {
    e.preventDefault();

    const client = {
      existing: this.state.existing,
    };

    console.log(client);

    axios
      .post("http://localhost:5000/clients/create", client)
      .then((res) => console.log(res.data));
  }

  render() {
    return (
      <>
        <form onSubmit={this.onSubmit}>
          
                    <div className="form-group">
                      <label>Existing Customer: </label>
                      <select
                        ref="userInput"
                        required
                        className="form-control"
                        value={this.state.existing}
                        onChange={this.onChangeExisting}
                      >
                        <option key="Male" value="Male">
                          Male
                        </option>
                        <option key="Female" value="Female">
                          Female
                        </option>
                      </select>
                    </div>
              <button type="submit" onClick={this.onSubmit}>submit </button> 
        </form>
      </>
    );
  }
}

【问题讨论】:

  • 我在这里没有发现任何问题。您能否分享您在此处提到的路线的服务器代码。

标签: node.js reactjs mongodb express


【解决方案1】:

You dont Have &lt;button&gt; Tag in side a &lt;form&gt; tag .

那么提交事件何时以及如何调用? 请添加

<button type="submit" onClick={this.onSubmit}>submit </button>  

在表单标签内。

【讨论】:

  • 哦,很抱歉,它确实在那里,可能不小心删除了它
【解决方案2】:

已经解决了,只需要更改 put 数据而不是 e

 onChangeExisting(e) {
    this.setState({
      existing: e.target.value,
    });
  }

 onChangeExisting(data) {
    this.setState({
      existing: data.value,
    });
  }

并像这样放置一个变量:

const existing= [
  { key: "Not Started", label: "Not Started", value: "Not Started" },
  { key: "In Progress", label: "In Progress", value: "In Progress" },
  { key: "Completed", label: "Completed", value: "Completed" },
];

并通过以下方式调用它:

npm i react-select

then import Select from "react-select";在你要使用的页面上

<Select options={existing} onChange={this.onChangeExisting} />

【讨论】:

    猜你喜欢
    • 2018-12-11
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 2014-02-12
    • 2017-03-02
    相关资源
    最近更新 更多