我正在使用Reaction中的列表项创建一个下拉列表,并映射数据以显示每个选项.我希望用户能够 Select 多个选项,并将所有选定的选项保存在州中.

目前,他们 Select 的最后一个选项保存在该州的数组中,但我无法将他们 Select 的所有选项保存在该州中,因为他们不能 Select 多个选项,因此它们只存储在前一个状态中.

如何将多个选定的列表项存储在州中的一个数组中?

 const [selectedSymptoms, setSelectedSymptoms] = useState(null)

                       const handleSymptoms = (symptom) => {
                       setSelectedSymptoms([symptom.Name])
                    // selectedSymptoms !== null && selectedSymptoms.push(symptom.Name)
                       console.log(selectedSymptoms)
                       }

                            <button
                            className={styles.selectSymptomBtn}
                            type="button"
                            onClick={toggleSymptoms}
                        >
                            Select your symptom
                        </button>

                        <ul className={`${isSymptomsOpen ? styles.show : styles.hide}`}>
                            {data.symptoms.map((symptom) => (
                                <li onClick={(() => handleSymptoms(symptom))}>
                                    {symptom.Name}
                                </li>))}</ul>

推荐答案

在这里,Set是最有意义的.这将防止用户在两次 Select 相同症状时添加重复项,而不必搜索整个array.

将函数传递给setSelectedSymptoms将使您可以访问以前的状态.

const [selectedSymptoms, setSelectedSymptoms] = useState(new Set());

const handleSymptoms = (symptom) => setSelectedSymptoms((prev) => prev.add(symptom.Name));

Set:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set的文档


您也可以展开此选项,以便在第二次单击时轻松取消 Select 症状

  const handleSymptoms = (symptom) =>
    setSelectedSymptoms((prev) =>
      prev.delete(symptom.Name) ? prev : prev.add(symptom.Name)
    );

编辑

在重读这篇文章时,我意识到解决方案介于不可变和可变之间.你不妨完全朝着一个方向或另一个方向前进.

Mutable solution

  const selectedSymptoms = useRef(new Set());
  const handleSymptoms = (symptom) => selectedSymptoms.current.add(symptom.Name);

Immutable solution

  const [selectedSymptoms, setSelectedSymptoms] = useState(new Set());
  const handleSymptoms = (symptom) =>
    setSelectedSymptoms((prev) => new Set(prev.values()).add(symptom.Name));

Reactjs相关问答推荐

eslint -无法解析模块的路径@web3modal/ethers/react导入/no-unresolved

无法覆盖MUI工具栏上的左右填充,除非使用!重要

如何使用react-router-dom导航到网页中的其他路由?

在Reaction中单击时,按钮未按预期工作

使用Reaction钩子窗体验证可选字段

有没有可能在next.js和ssr中使用tsps?

使用VITE的Reaction应用程序的配置是否正确?

错误:无法获取 RSC 负载.返回浏览器导航

console.logs 没有显示在浏览器控制台上,但显示在我的终端上

React-router动态路径

Mui / Material UI 5:如何从 StaticTimePicker 中删除打开下一个视图/打开上一个视图按钮?

Reactjs:MUI5:MobileDateTimePicker API:如何自定义日历中的文本

无法通过react 路由中的链接传递信息

使用D3.js绘制和展示弦图的右下方象限

未处理的拒绝 (TypeError):无法读取未定义的属性(读取协议)

将复杂状态和 setState 传递给更简单的 api

React Native PermissionsAndroid 不包括 READ_MEDIA_IMAGES.如何解决这个问题?

getAttribute 函数并不总是检索属性值

仅在重新渲染后设置状态

a.active 类在导入 x.scss 文件时有效,但在使用 x.module.scss 时无效