【问题标题】:Why won't my controlled Input component in React update with the state?为什么我在 React 中受控的 Input 组件不会更新状态?
【发布时间】:2020-03-10 10:00:35
【问题描述】:

我在我所在的州的“editIngreds”数组中有一个成分列表,例如['苹果','香蕉','橙色']。它们通过 react map 函数渲染到 DOM。我有一个编辑模式,用输入框替换文本,这样我就可以编辑项目并将它们保存回状态数组。但是,在框中键入时,没有任何反应。 console.log 显示当我输入字符时 editIngreds[i] 确实在更新,但是输入框不会用这个新值更新。

 export default function RecipeCard({ recipe, onEditRecipe, onRemoveRecipe }) {
      const ingredients = Object.values(recipe.ingredients);
      const ingredientKeys = Object.keys(recipe.ingredients);

      const [editIngreds, setEditIngreds] = React.useState(ingredients)

      ...

      const onChangeEditIngreds = (event, i) => {
        const value = event.target.value;
        const ingreds = editIngreds
        ingreds[i] = value;
        setEditIngreds(ingreds);
      };

      ...

      return (
        <ul>
          {ingredients.map((ingred, i) => (
            <li key={ingredientKeys[i]}>
              {editMode ? (
                <Input
                  type="text"
                  value={editIngreds[i]}
                  onChange={(e) => onChangeEditIngreds(e,i)}
                />
               ) : (
                 <>{ingred}</>
               )}
             </li>
           ))}
         </ul>

【问题讨论】:

    标签: javascript arrays reactjs


    【解决方案1】:

    你正在改变state。在更新之前制作ingredients 的浅拷贝

    const onChangeEditIngreds = (event, i) => {
        const value = event.target.value;
        const ingreds = [...editIngreds];
        ingreds[i] = value;
        setEditIngreds(ingreds);
      };
    

    【讨论】:

    • Np @Sam,很乐意提供帮助。感谢 Dupcas 的编辑。
    【解决方案2】:

    而不是使用这个 -> ingredients.map((ingred, i) 使用这个 ->

    editIngreds.map((ingred, i){
    ....
    
    <Input
          type="text"
          value={ingred}
          onChange={(e) => onChangeEditIngreds(e,i)}
     />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多