![](/img/trans.png)
[英]Uncaught TypeError: Cannot read property 'setState' of undefined
[英]Uncaught TypeError: Cannot read property 'setState' of undefined at handleChange , Cannot read property 'props' of null at handleSubmit
我是React-redux堆棧的新手,我正在學習基本知識,現在被困住了。 我想將表單數據保存在mongodb中,但沒有任何障礙。 我收到這兩個錯誤,如何幫助將這些表格數據插入數據庫。 在此感謝
這是我的form.js頁面。 我從此處將數據發送到action.js頁面,然后發送到server.js,然后發送到controller.js,在這里我導入模型並嘗試保存數據。
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import Messages from '../Messages';
import classnames from 'classnames';
import saveBasicUser from '../../actions/basicAction';
class BasicUser extends React.Component {
constructor(props) {
super(props);
this. state = {
username : '',
address : '',
phone : '',
date : '',
billing : ''
}
}
handleChange (e) {
this.setState({ [e.target.name]: e.target.value });
}
//========================================================================
handleSubmit(e) {
e.preventDefault();
this.props.saveBasicUser({ username, address, phone, date, billing });
}
//========================================================================
render() {
var divStyle = {
padding: '16',
};
return (
<div className="container ca-container">
<div className="row">
<div className="col-md-12">
<h1> ADD basic USER</h1>
<hr/>
</div>
</div>
<form onSubmit={this.handleSubmit}>
<label > Name : </label>
<input className= "form-control" id = "username" name = "username" value={this.state.username}
onChange={this.handleChange} />
<label > address : </label>
<input className= "form-control" id = "address" name = "address" value={this.state.address}
onChange={this.handleChange} />
<label > Phone No: : </label>
<input className= "form-control" id = "phone" name = "phone" value={this.state.phone}
onChange={this.handleChange}/>
<label > Subscription date : </label>
<input className= "form-control" id = "date" name = "date" type ="date" value={this.state.date}
onChange={this.handleChange}/>
<label > Billing : </label>
<input className= "form-control" name = "billing" id = "billing" value={this.state.billing}
onChange={this.handleChange}/>
<hr />
<button type="submit" value= "submit" className="btn btn-success btn-lg">Submit</button>
</form>
</div>
);
}
}
export default connect (null , {saveBasicUser})(BasicUser);
你有你的綁定handleChange
和handleSubmit
功能BasicUser
otherwhise this
將undefined
。 有很多方法可以做到,但是最簡單的方法是將函數用作類屬性(使用箭頭函數保留類范圍)。
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
}
handleSubmit = e => {
e.preventDefault();
this.props.saveBasicUser({ username, address, phone, date, billing });
}
該語法由ES7帶來,您可能需要此babel插件才能使用它。
如果您不想安裝插件,另一種簡單的方法是在render()
使用箭頭函數:
<input onChange={e => this.handleChange(e)} />
將這兩行放在構造函數中。 我認為您沒有使用babel,這就是為什么您不能使用箭頭的原因。
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.