简体   繁体   English

为什么我在 React 中的受控输入组件不会更新为 state?

[英]Why won't my controlled Input component in React update with the state?

I've got a list of ingredients in an "editIngreds" array in my state, eg ['Apple', 'Banana', 'Orange'].我的 state 的“editIngreds”数组中有一个成分列表,例如 ['Apple'、'Banana'、'Orange']。 They are rendered to the DOM via react map function.它们通过 react map function 渲染到 DOM。 I have an edit mode that replaces the text with Input boxes so I can edit the items and save them back to the state array.我有一个编辑模式,用输入框替换文本,因此我可以编辑项目并将它们保存回 state 数组。 However, when typing in the box, nothing happens.但是,在框中键入时,没有任何反应。 console.log shows that editIngreds[i] is indeed being updated when I type a character, however the input boxes do not update with this new value. 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>

You are mutating the state .您正在改变state Make a shallow copy of ingredients before updating在更新之前制作ingredients的浅拷贝

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

Rather than using this -> ingredients.map((ingred, i) use this ->而不是使用这个 -> 成分.map((ingred, i) 使用这个 ->

editIngreds.map((ingred, i){
....

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM