React如何根据数组键值动态修改状态 点击li项展示对应关联数据
实现方案
你需要通过状态记录当前点击的列表项索引,再根据索引读取对应位置的展示数据即可,可根据你的需求选择以下两种写法:
写法1:按需取数(性能更优)
无需提前遍历全量数组,点击时根据选中索引取对应位置的字段值:
import { useState } from 'react'; // 你的组件逻辑 const YourComponent = ({ ProductDetail }) => { // 新增状态记录当前选中的列表项索引,默认选中第一个,不需要默认展示可设为null const [selectedIndex, setSelectedIndex] = useState(0); // 提前做数据兜底,避免空值报错 const functionalList = ProductDetail?.chart?.functionalsInfo || []; // 根据选中索引取对应数据 const selectedIngredient = functionalList[selectedIndex]?.materialsInfo?.[0]?.ingredientsInfo?.[0] || {}; const selectedName = selectedIngredient.chartStatus || ''; const selectedBarVal = selectedIngredient.ingredientDisplayText || ''; return ( <> <ul> {functionalList.length ? ( functionalList.map((Info, index) => ( <li key={Info.id} onClick={() => setSelectedIndex(index)} style={{ cursor: 'pointer' }} // 可选,加鼠标手势提示可点击 > {Info.seedShapeDisplayText} </li> )) ) : <li>There is not</li>} </ul> <div> Hi Number {selectedName}, Bar : {selectedBarVal} <Bar labels={[selectedBarVal]} /> </div> </> ) }
写法2:兼容原有全量数组提取逻辑
保留你原本提前提取functionInfolabels、NumberStatus全量数组的写法:
import { useState } from 'react'; const YourComponent = ({ ProductDetail }) => { const [selectedIndex, setSelectedIndex] = useState(0); const functionalList = ProductDetail?.chart?.functionalsInfo || []; // 你原有提取全量数组的逻辑,加空值兜底 const functionInfolabels = ProductDetail?.chart?.functionalsInfo?.[0].materialsInfo?.[0].ingredientsInfo?.map(array => array.ingredientDisplayText) || []; const NumberStatus = ProductDetail?.chart?.functionalsInfo?.[0].materialsInfo?.[0].ingredientsInfo?.map(array => array.chartStatus) || []; return ( <> <ul> {functionalList.length ? ( functionalList.map((Info, index) => ( <li key={Info.id} onClick={() => setSelectedIndex(index)} style={{ cursor: 'pointer' }} > {Info.seedShapeDisplayText} </li> )) ) : <li>There is not</li>} </ul> <div> Hi Number {NumberStatus[selectedIndex] || ''}, Bar : {functionInfolabels[selectedIndex] || ''} <Bar labels={functionInfolabels} /> </div> </> ) }
内容的提问来源于stack exchange,提问作者ssksksks
相关产品推荐
相关产品推荐

