【发布时间】:2021-01-23 21:54:48
【问题描述】:
我只是想删除我页面上的一个项目。当我删除该项目时,我得到这个 Unhandled Rejection (TypeError): state.recipes is undefined 消息指向我的减速器。当我刷新页面时,对象消失了,错误消失了。问题是在删除项目之前导致此错误的原因是什么?
这是我单击删除按钮后发生的情况,当我刷新页面时,对象消失了。
case 'DELETING_RECIPE_START':
return {
...state.recipes,
loading: true
}
case 'DELETE_RECIPE_SUCCESS':
This line -----> const recipes = state.recipes.filter(recipe => recipe.id !== action.payload.recipeId)
return {
...state, recipes,
loading: false
}
有人告诉我在这种情况下是检查后端的删除操作。当我插入 byebug 时,它显示我正在尝试删除哪个对象,所以希望它没有我需要担心的。
def destroy
recipe = Recipe.find(params[:id])
unless recipe.nil?
recipe.destroy
render json: recipe
else
render json: { error: "Property not found" }, status: 404
end
end
我确实将删除操作修改为 thunk 异步约定,我希望它的结构正确。我会注意到,当我在 return(dispatch) 之前运行调试器时,我的错误问题似乎发生在 return(dispatch) 行之后。
export const deleteRecipe = (recipeId) =>{
const BASE_URL = `http://localhost:3001`
const RECIPES_URL =`${BASE_URL}/recipes`
debugger
return (dispatch) => {
dispatch({ type: "DELETING_RECIPE_START" })
fetch(`${RECIPES_URL}/${recipeId}`,{method: 'DELETE'})
.then(response =>{return response.json()})
.then(recipeId => dispatch({ type: 'DELETE_RECIPE_SUCCESS', payload: recipeId }))
.catch((error) => console.log.error(error))
};
}
最后是我的 Recipe 组件,其中包含删除按钮和关联的事件处理程序。
class Recipe extends Component {
handleOnClick(){
this.props.deleteRecipe(this.props.recipe.id);
}
render(){
return(
<div>
<h3>Name: {this.props.recipe.name}</h3>
<p>Category:{this.props.recipe.category_id}</p>
<p>Chef Name: {this.props.recipe.chef_name}</p>
<p>Origin: {this.props.recipe.origin}</p>
<p>Ingredients: {this.props.recipe.ingredients}</p>
<button onClick={()=>this.handleOnClick()}>Delete</button>
</div>
)
}
}
export default Recipe
我能做些什么来纠正这个问题?
【问题讨论】:
标签: javascript ruby-on-rails reactjs react-redux