在没有onClick触发器的情况下,在渲染中发出AJAX请求
问题描述:
昨天我开始自学一些React。我有一个登录表单,当按钮被点击时,它应该发送一个AJAX请求到我的后端。这有效,当我的后端没有运行时,这意味着:我的自写后端(用邮递员测试)必须关闭,以便它不回复并且可以呈现页面。 当它运行时,虽然方法在渲染上被调用,但这绝对不是我想要的,因为我的后端发送了一个错误,并且页面没有渲染。在没有onClick触发器的情况下,在渲染中发出AJAX请求
我反应过来的代码是在这里:
构造函数:
constructor(props)
{
super(props);
this.login = this.login.bind(this);
this.handleChangeUser = this.handleChangeUser.bind(this);
this.handleChangePassword = this.handleChangePassword.bind(this);
this.logout = this.logout.bind(this);
this.state = {
user: '',
password: '',
loggedIn: props.loggedIn
};
}
的形式为:
return (
<div>
<Navigation/>
<div style={{position: "relative", left: "30%", right: "70%"}}>
<label>Username</label><br/>
<input type={'text'} onChange={this.handleChangeUser} style={{width: "300px"}}/><br/>
<label>Password</label><br/>
<input type={'password'} onChange={this.handleChangePassword} style={{width: "300px"}}/><br/>
<div style={{width: "300px"}}>
<button type={"button"} className={"btn btn-primary"} style={{marginTop: "10px"}} onClick={this.login}>
Login
</button>
</div>
</div>
</div>
);
,这是导致所有麻烦的登录功能:
login(e)
{
e.preventDefault();
axios({
method: 'get',
url: BASE_URL + LOGIN,
data: {
user: this.state.user,
password: this.state.password
}
}).then(function (result)
{
localStorage.setItem('botusToken', result.body.token);
this.setState({loggedIn: true});
}).catch(function()
{
console.log("Error while login in");
});
}
Th比如是就像一个魅力:
render()
{
return (
<div>
<form>
<label htmlFor="comment">Some comment</label>
<label htmlFor="triggerWord">Which trigger-word would you like your tweet to belong to?</label>
<select className={"form-control"} onChange={this.handleChangeSelector}>
<option>Sad</option>
<option>Fake News</option>
<option>Taxes</option>
<option>Immigrants</option>
<option>Make America Great Again</option>
<option>Make a new trigger word</option>
</select>
<Textarea className={"form-control"} rows={2} cols={50} maxLength={140} wrap={"soft"}
onChange={this.handleChangeTextArea} value={this.state.tweet}/>
</form>
<br/>
<button type={"button"} className={"btn btn-primary"} onClick={this.submitTweet}>Submit</button>
<div style={errStyle}>{this.state.err}</div>
</div>
);
};
这种方法就像一个魅力在和谐与上述表单:
submitTweet(e)
{
let self = this;
e.preventDefault();
let isNew = false;
if (this.state.topic === "Make a new trigger word") isNew = true;
axios({
method: 'post',
url: BASE_URL + SUBMIT_TWEET,
data: {
topic: this.state.topic,
tweet: this.state.tweet,
new: isNew
}
}).then(function()
{
self.setState({err: ''});
}).catch(function (err)
{
self.setState({err: "You have not entered all necessary information!"});
});
this.setState({tweet: ''});
};
感谢您抽空看看!
答
如何改变onClick={() => this.login}
到onClick={(e) => this.login(e)}
的this.login渐渐呼吁渲染。这就是为什么当后端未运行时渲染正在进行。
要在React类中绑定函数,可以在构造函数中使用绑定调用或在标记中使用箭头函数。
如果您要提交表单,您不应该''''而不是'GET'ing? – Andy
//当我的后端没有运行//你能解释这个说法吗?另外分享你的完整代码...你需要定义按钮类型=“按钮” –
发布错误消息,如果有的话 – hawk