点击时状态不会更新

问题描述 投票:0回答:1

我的食谱项目有问题。在此

section
中,用户可以添加他们的食谱步骤。用户单击加号按钮添加
textarea
来编写新步骤,单击减号按钮删除步骤。

加号按钮工作正常,单击时会添加

textarea
,但是,我遇到的问题是,当用户删除步骤时,状态不会更新,直到用户再次单击加号按钮。我不知道为什么减号按钮不像加号按钮那样立即更新。

这些是添加和删除功能

type Textbox = {
  readonly id: string;
  index: number;
};

 const [textboxes, setTextboxes] = useState<Textbox[]>([]);

 const handleAddTextBox = () => {
    const textbox = {
      id: uniqid(),
      index: textboxes?.length + 1,
    };

    const allTextBoxes = [...textboxes, textbox];
    setTextboxes(allTextBoxes);
  };

  const handleRemoveTextBox = () => {
    if (textboxes.length <= 1) {
      alert("You need at least one step. Try being more descriptive.");
    } else {
      textboxes.pop();
    }
  };

这是我实现它们的地方

<section className={`${styles.section5} ${styles.section}`}>
            <div className={styles.field}>
              <h1 className={styles.label}>instructions</h1>
              <div className={styles["step-list"]}>
                {textboxes.map((box: { id: string; index: number }) => (
                  <div className={styles.step} key={box.id}>
                    <label htmlFor={box.id} className={styles.index}>
                      step {box.index}
                    </label>
                    <textarea
                      name={box.id}
                      id={box.id}
                      cols={100}
                      rows={3}
                      className={styles.textbox}
                      ref={instructionRef}
                    ></textarea>
                  </div>
                ))}
              </div>

              {/* Add textbox button */}
              <button
                className={`${styles.icon} ${styles.add}`}
                onClick={handleAddTextBox}
                type="button"
              >
                <i className="fa-solid fa-plus"></i>
              </button>

              {/* Remove textbox button */}
              <button
                className={`${styles.icon} ${styles.remove}`}
                onClick={handleRemoveTextBox}
                type="button"
              >
                <i className="fa-solid fa-minus"></i>
              </button>
            </div>
          </section>

我还提供了一个指向我的 GitHub 存储库的链接,您可以在其中查看我的其余源代码,以防这还不够或者我正在做的其他事情影响了我的问题。前往

src/components/Post/PostForm.tsx
查看相关代码。 源代码

javascript reactjs typescript state
1个回答
0
投票

听起来您的删除步骤函数中的状态更新方式可能存在问题。确保您正确更新状态并在单击减号按钮时触发重新渲染。

以下是如何处理 React 组件中添加和删除步骤的一般示例:

import React, { useState } from 'react';

const RecipeForm = () => {
  const [steps, setSteps] = useState(['']); // Initial state with an empty step

  const addStep = () => {
    setSteps([...steps, '']); // Adding a new empty step
  };

  const removeStep = (index) => {
    const updatedSteps = [...steps];
    updatedSteps.splice(index, 1); // Removing the step at the specified index
    setSteps(updatedSteps); // Updating the state
  };

  return (
    <div>
      {/* Display existing steps */}
      {steps.map((step, index) => (
        <div key={index}>
          <textarea
            value={step}
            onChange={(e) => {
              const updatedSteps = [...steps];
              updatedSteps[index] = e.target.value;
              setSteps(updatedSteps);
            }}
          />
          <button onClick={() => removeStep(index)}>-</button>
        </div>
      ))}

      {/* Button to add a new step */}
      <button onClick={addStep}>+</button>
    </div>
  );
};

export default RecipeForm;

此示例在添加或删除步骤时使用扩展运算符创建一个新数组,确保您不可变地更新状态。如果问题仍然存在,您可能需要提供更多详细信息或检查代码的其他部分以查找潜在原因。

© www.soinside.com 2019 - 2024. All rights reserved.