首页 > 解决方案 > React.js - 功能组件中的状态未更新

问题描述

我有一个功能组件,它带有一个名为“checked”的状态钩子,它是一个用于复选框列表的布尔数组。单击复选框时,我有一个更新状态的事件处理程序,因此该复选框将呈现一个复选或一个空框。

根据我的函数中的 console.logs,状态正在更新,但复选框在浏览器中没有响应,并且开发工具确认状态没有更新。如果我使用开发工具手动切换状态,复选框就可以正常工作,所以我认为这是状态不更新的问题。任何建议将不胜感激!

import React, { useState, useContext } from 'react';

export default function MessengerCheckboxes() {
 const [checked, setChecked] = useState([false, false, false]);

...

 const handleChangeChild = (event) => {
   console.log('Currently state is: ' + checked); // Currently state is: [false, false, false]

   let index = parseInt(event.target.id.slice(0, 1));
   let localChecked = checked; //
   localChecked[index] = !checked[index];
    
   console.log('State should be: ' + localChecked); //State should be: [true, false, false] [[for example]]
   setChecked(localChecked);
    
   setTimeout(() => { // Added setTimeout for troubleshooting to make sure I wasn't calling state too quickly after setting it
       console.log('State is now: ' + checked); // State is now: [true, false, false] [[but won't trigger re-render and dev tools show state is [false, false, false]]
   }, 1 * 1000);
 };
}

我的 console.log 的图像

我的开发工具的图片

非常感谢您提前!

标签: reactjsreact-hooksstatereact-state

解决方案


你不应该像那样更新状态。

在这种情况下,需要一个更复杂的状态对象。我喜欢使用一个对象来保持列表中每个项目的状态。检查此链接:https ://codesandbox.io/s/checkbox-state-https-stackoverflow-com-questions-69680938-react-js-state-not-updating-in-functional-component-di0dd

import "./styles.css";
import { useState } from "react";

export default function App() {
  // 1.
  const stateObj = {
    cb1: false,
    cb2: false,
    cb3: false
  };
  const [cbState, setCbState] = useState(stateObj);
  const handleCb = (event) => {
    console.log(event.target.name, event.target.checked);
    // 4.
    setCbState({ ...cbState, [event.target.name]: event.target.checked });
  };
  return (
    <div>
      <input
        type="checkbox"
        name="cb1" // 2.
        onChange={handleCb}
        value={cbState["cb1"]} // 3.
      />
      <input
        type="checkbox"
        name="cb2"
        onChange={handleCb}
        value={cbState["cb2"]}
      />
      <input
        type="checkbox"
        name="cb3"
        onChange={handleCb}
        value={cbState["cb3"]}
      />
    </div>
  );
}

所以要带走,分步骤:

  1. 创建/准备状态对象 - 键将用作 html 元素的名称
  2. 为 html 元素设置名称属性 - 使用与 1 相同的键。
  3. 为 html 元素设置值属性 - 使用state['key']. 这就是您实现受控组件的方式
  4. 以持久化现有数据/值(使用扩展运算符)+更新(用于访问属性的括号表示法)的方式设置状态。在这个例子中,我们使用事件namechecked属性来实现它。

推荐阅读