如何基于动态键值正确渲染列表?解决配置跳转后列表不显示问题
问题解决思路
核心是利用已有的prevListKey状态作为currentListKey的 fallback,同时确保在关键操作点(Configure点击、保存)正确维护currentListKey的值,无需新增状态。
具体修改步骤
1. 调整列表渲染逻辑,增加fallback机制
将渲染时依赖的currentListKey替换为currentListKey || prevListKey,确保当currentListKey未设置时,自动使用点击Configure时已保存的prevListKey获取数据:
{(formValues[currentListKey || prevListKey] && formValues[currentListKey || prevListKey].length > 0) && ( <ul> {formValues[currentListKey || prevListKey]?.map((item, index) => { return ( <li key={index}> {item.name} <button type="button" onClick={() => { setFormType(nextForm); setFormStates((prevState) => ({ ...prevState, [currentForm]: formValues })); setSelectedItem(item); setListItem(item); setPrevListKey(currentListKey); // 强化状态一致性,避免后续操作丢失列表键 setCurrentListKey(currentListKey); }}> Configure </button> <button type="button" onClick={() => { const activeKey = currentListKey || prevListKey; setFormValues((prevState) => ({ ...prevState, [activeKey]: prevState[activeKey].filter((_e, i) => i !== index), })); setSelectedOptions((prevState) => prevState.filter((option) => option._id !== item._id)); }}> Remove </button> </li> ); })} </ul> )}
2. 补充取消配置时的列表键恢复逻辑(若有取消按钮)
如果存在取消配置的按钮,在其点击事件中添加列表键恢复逻辑,确保返回后currentListKey被正确设置:
<button type="button" onClick={() => { setFormType(currentForm); setCurrentListKey(prevListKey); }}> Cancel </button>
3. 保留handleSave函数的现有逻辑
现有handleSave函数中已包含setCurrentListKey(prevListKey),这部分逻辑可以保留,确保保存操作完成后currentListKey被正确重置为之前的列表键。
核心逻辑说明
- 渲染时通过
currentListKey || prevListKey双保险,彻底避免因currentListKey未设置导致的列表不渲染问题; - 点击Configure时额外设置
currentListKey,强化状态一致性,防止异步操作导致的状态丢失; - 删除操作时使用统一的
activeKey变量获取当前有效的列表键,避免因键值为空引发的错误。
内容的提问来源于stack exchange,提问作者BraulioPortela
相关产品推荐
相关产品推荐

