[英]React Event Handler Button Click Not Working on First Click
我正在Free Code Camp制作Recipe Box項目。 我有一個事件處理程序,該事件處理程序應該發送一個對象,該對象包含由成分組成的數組屬性,直到父組件,該父組件將在數組中顯示項目。 問題是,當我第一次單擊觸發處理程序的按鈕時,即使用戶輸入了成分,它也會發送一個空數組,而當我第二次單擊它時,它將發送上次單擊按鈕時的成分,並且每次單擊該按鈕時都將繼續這樣。 我怎樣才能解決這個問題?
有問題的方法:
handleSubmit() {
let ingredientsArrayUpdater = (ingredient) => {
this.setState(prevState => ({
ingredientsArr: [
...prevState.ingredientsArr,
ingredient
]
}))
}
let splitUserInput = this.state.ingredients.split(',');
splitUserInput.map(ingredient => {
return(
ingredientsArrayUpdater(ingredient.trim())
)
});
let recipeObject = {
recipeName: this.state.recipe,
ingredientList: this.state.ingredientsArr,
idNumber: Math.floor((Math.random() * 100000000) + 1)
}
this.props.addRecipe(recipeObject);
}
觸發事件處理程序的按鈕的代碼:
<button onClick={e => {this.handleSubmit()}}
className="btn btn-outline-success btn-sm">
Add Recipe
<i className="fas fa-plus"></i>
</button>
這是查看所有組件的github存儲庫。 Index.js是父組件。
https://github.com/EsTrevino/recipe-box-project/tree/master/src
首先,您不會以自己認為的狀態更新狀態。 在調用setState
之后,您也不必等待更新的狀態。 我不確定您要使用此方法實現的所有功能,但是一個開始是:
handleSubmit() {
let splitUserInput = this.state.ingredients.split(',');
let newArray = this.state.ingredientsArr.concat(splitUserInput.map(a => a.trim()));
this.setState({ingredientsArr: newArray});
let recipeObject = {
recipeName: this.state.recipe,
ingredientList: newArray,
idNumber: Math.floor((Math.random() * 100000000) + 1)
}
this.props.addRecipe(recipeObject);
}
使用我們知道的狀態將被更新為“欺騙”。 您也可以使用回調使setState
更具單向性。
handleSubmit() {
let splitUserInput = this.state.ingredients.split(',');
let newArray = this.state.ingredientsArr.concat(splitUserInput.map(a => a.trim()));
this.setState({ingredientsArr: newArray}, () => {
let recipeObject = {
recipeName: this.state.recipe,
ingredientList: newArray,
idNumber: Math.floor((Math.random() * 100000000) + 1)
}
this.props.addRecipe(recipeObject);
});
}
IMO,同樣的區別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.