昨天我開始自學一些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: ''});
};
感謝您抽空看看!
如果您要提交表單,您不應該''''而不是'GET'ing? – Andy
//當我的後端沒有運行//你能解釋這個說法嗎?另外分享你的完整代碼...你需要定義按鈕類型=「按鈕」 –
發佈錯誤消息,如果有的話 – hawk