我有一個Login
組件:陣營:不能從孩子得到國家於母公司
var React = require('react');
var LoginForm = require('./LoginForm');
class Login extends React.Component {
constructor (props) {
super(props)
// Bind the this context to the handler function
this.handler = this.handler.bind(this);
// Set some state
this.state = {
username: '',
password: '',
token: ''
};
}
handler(data) {
this.setState(data);
}
render() {
return (
<div className="login-container">
<div className="outer">
<div className="middle">
<div className="inner">
<LoginForm loginHandler={this.handler}/>
</div>
</div>
</div>
</div>
)
}
}
module.exports = Login;
和LoginForm
之一:
var React = require('react');
import axios from 'axios';
class LoginForm extends React.Component {
handleLoginClick(event) {
event.preventDefault();
var apiBaseUrl = "http://localhost:8000/api-token-auth/";
var payload={
"email": "[email protected]",
"password": "thePassword"
};
axios.post(apiBaseUrl, payload)
.then(function (response) {
console.log(response);
var data = {
username: '[email protected]',
password: 'thePassword',
}
this.props.loginHandler(data) . // <-- FAILS HERE. this is undefined
})
.catch(function (error) {
alert('NO');
console.log(error);
});
}
render() {
return (
<form>
<input type="text" className="form-control" name="username" placeholder="Email Address" required="" />
<input type="password" className="form-control" name="password" placeholder="Password" required=""/>
<p></p>
<button onClick={(event) => this.handleLoginClick(event)} className="btn btn-lg btn-primary btn-block">Login</button>
</form>
)
}
}
module.exports = LoginForm;
我知道實際的愛可信功能應該做過的工作,但我的問題是不同的:我似乎無法獲得用戶名,密碼和令牌信息給父母。該函數在上面顯示的地方未定義,並且無法從子項訪問處理函數,因此失敗。我在這裏做錯了什麼?
什麼是不確定的? 'LoginForm'或'loginHandler'函數中的'data'? –
無法讀取未定義的屬性'道具'。這個this.props在LoginForm中是未定義的 – JasonGenX
在''email「:」[email protected]「,// this.state.username'中,'this'是指你的'LoginForm'沒有定義狀態。 – wesley6j