[英]react/nodejs: Receiving value from a select dropdown to send it to the database
I'm having a select dropdown in my react frontend like this 我在我的反应前端中有一个选择下拉列表
<select name="level" value={level} onChange={this.handleChange} className="form-control"> <option>Begineer</option> <option>Intermediate</option> <option>Advanced</option> </select>
I'm handling this value as req.body in my backend. 我在后端将这个值作为req.body处理。 My handleChange function is simply
我的handleChange函数很简单
handleChange(event) { const state = this.state; state[event.target.name] = event.target.value; this.setState({ state }); }
When i submit the form, this value does not gets submitted. 当我提交表单时,此值不会被提交。 I'm also intitializing this value in my constructor function.
我还在我的构造函数中初始化了该值。 What can i do in this case?
在这种情况下我该怎么办?
一定是
this.setState(state)
first of all you need to ad the value to your options 首先,您需要将价值推广到您的选择中
<option value="Begineer">Begineer</option>
second of all never mutate the state object directly without set state like this 第二,永远不要在没有设置状态的情况下直接改变状态对象
state[event.target.name] = event.target.value;
instead 代替
let objToUpdate = {...state};
objToUpdate[event.target.name]= event.target.value
this.setState(objToUpdate)
this should solve your issue 这应该可以解决您的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.