reactjs - 从回调状态更改后反应组件未呈现
问题描述
我正在尝试构建一个小型 Web 应用程序以将食谱保存到数据库中,但我遇到了一个问题,即食谱视图组件使用回调来更新父级的状态,但调用回调时父级未呈现。
复制回购:Github
如果从页面内更改状态,则一切正常。当通过子组件的回调更新状态时,没有任何反应。
任何人都可以看看并帮助我吗?我已经找了2-3个小时了。
谢谢
解决方案
您正在改变您的状态,而不是更新不可变的状态。
您需要创建一个新对象以保存到状态中,而不是更改现有对象并更新它:
const handleChangeField = (field: string) => (e: ChangeEvent<HTMLInputElement>) => {
console.log("change field", field, "to", e.target.value)
const tempRecipe = recipe;
tempRecipe[field] = e.target.value; // You are changing the already saved object
//if (field === "title") tempRecipe["name"] = recipeTitleToName(e.target.value)
console.log("call onchange")
onChange(tempRecipe)
}
将其更改为:
const handleChangeField = (field: string) => (e: ChangeEvent<HTMLInputElement>) => {
console.log("change field", field, "to", e.target.value)
const tempRecipe = {...recipe}; // This is now a new object and React will not skip the render
// @ts-ignore
tempRecipe[field] = e.target.value;
//if (field === "title") tempRecipe["name"] = recipeTitleToName(e.target.value)
console.log("call onchange")
onChange(tempRecipe)
}
推荐阅读
- amazon-web-services - 保护网站管理面板访问的选项 - 只有受信任的用户才能访问它
- iptables - 如何通过 iptables 阻止 FIN-WAIT-2?
- javascript - 在聊天应用程序中获取最新消息 - Django
- nginx - Nginx 反向代理到两个服务
- java - 尝试使用 apache POI 从 excel 表中检索数据
- php - (PHP) 试图控制包含函数
- r - R ggplot2 geom_bar barplot:在不修改数据框的情况下按计数对条形图进行排序,并且因子标签具有含义
- python-datetime - 通过排除 pandas 数据框中的非营业时间来计算两个日期之间的营业时间
- azure - 通过 API 检索 Azure AppInsights 实时指标
- vue.js - Vue没有看到从单独组件传递的函数