【问题标题】:React Checkbox Form State is Delayed反应复选框表单状态延迟
【发布时间】:2020-06-22 13:45:12
【问题描述】:

我有一个表单,我将复选框输入列表映射到使用 React。映射函数接收 JSON 对象列表并将它们映射到输入,如下所示:

const listCustomBenefits = props.customBenefits.map(benefit => {
    return(
        <div className="flex">
            <input onChange={props.handleCustomBenefitsChange} id={benefit.id} key={benefit.id} 
               className="my-auto" type="checkbox" checked={benefit.included}></input>
            <p className="my-auto px-2">{benefit.benefit}</p>
        </div>
        )
})

props.customBenefit 的格式如下:

const customBenefit = useState([
  {
    benefit: "first benefit description",
    id: 1,
    included: false,
    name: "First Benefit",
  },
  {
    benefit: "second benefit description",
    id: 2,
    included: false,
    name: "Second Benefit",
  },
]);

listCustomBenefits 然后在组件的返回 JSX 中返回。单击复选框时,handleCustomBenefitsChange 会更新自定义福利的状态,如下所示:

const handleCustomBenefitsChange = (event) =>{
    event.preventDefault()
    const newCustomBenefits = customBenefits.map(benefit =>{
        if(benefit.id == event.target.id){
            const newCheck = [event.target.checked][0]
            return({...benefit,  included: newCheck})
        }
        else{
            return benefit
        }
    })

    setCustomBenefits(newCustomBenefits)
 }

该函数会正确更新customBenefits 的状态,但复选框显示总是落后一个事件(即您必须单击复选框两次才能看到所需的更改)。

我也尝试在本地组件上使用道具设置状态(而不是直接使用道具),但似乎无法让组件在初始点击时更新。谁能帮我解决这个问题?

【问题讨论】:

  • 请勾选html

标签: reactjs forms checkbox checkboxlist


【解决方案1】:

我没有详细说明原因,但我认为这与 newCheck 已过时有关。我们可以翻转benefit.included 并绕过id 而不是依赖dom 状态,而不是从事件目标中获取它。

所以我们的复选框看起来像这样

<input
  onChange={() => handleCustomBenefitsChange(benefit.id)}
  ...
/>

我们的处理程序更改为接受 ID 而不是事件,并根据它自己的状态而不是 dom 进行更改

  const handleCustomBenefitsChange = id => {
    const newCustomBenefits = customBenefits.map(benefit => {
      if(benefit.id == id){
        return({...benefit,  included: !benefit.included})
    } else {
        return benefit;
      }
    });

    setCustomBenefits(newCustomBenefits);
  };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 2021-03-12
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 2019-06-07
    • 2021-01-24
    相关资源
    最近更新 更多