首页 > 解决方案 > 从回调状态更改后反应组件未呈现

问题描述

我正在尝试构建一个小型 Web 应用程序以将食谱保存到数据库中,但我遇到了一个问题,即食谱视图组件使用回调来更新父级的状态,但调用回调时父级未呈现。

复制回购:Github

如果从页面内更改状态,则一切正常。当通过子组件的回调更新状态时,没有任何反应。

任何人都可以看看并帮助我吗?我已经找了2-3个小时了。

谢谢

标签: reactjstypescript

解决方案


您正在改变您的状态,而不是更新不可变的状态。

您需要创建一个新对象以保存到状态中,而不是更改现有对象并更新它:

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)
  }

推荐阅读