reactjs - 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);
};
}
非常感谢您提前!
解决方案
你不应该像那样更新状态。
在这种情况下,需要一个更复杂的状态对象。我喜欢使用一个对象来保持列表中每个项目的状态。检查此链接: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>
);
}
所以要带走,分步骤:
- 创建/准备状态对象 - 键将用作 html 元素的名称
- 为 html 元素设置名称属性 - 使用与 1 相同的键。
- 为 html 元素设置值属性 - 使用
state['key']
. 这就是您实现受控组件的方式 - 以持久化现有数据/值(使用扩展运算符)+更新(用于访问属性的括号表示法)的方式设置状态。在这个例子中,我们使用事件
name
和checked
属性来实现它。
推荐阅读
- c# - 无空格字符串中最常见的词
- css - Tailwind CSS 和 Alpine JS 过渡问题
- saml - 每 10 分钟向 IdP 发送 SAML AuthnRequest
- javascript - 如何控制用户的尝试次数并将其存储在数组中并在 JS 中显示数组?
- powerbi - Power BI:将列表转换为表格
- javascript - 反应时间实现中的秒静态
- pandas - 按自定义顺序订购情节图例
- c# - C# & ASP.NET MVC:如何在另一个模型中填充数据对象模型
- visual-studio - Visual Studio 2019:调试期间“本地”面板出错 - “检索本地值的内部错误”
- react-native - React-Redux 不更新 SetInterval 上的值