设置controlShouldRenderValue为true的Multi select组件在表格中工作异常:选中内容仅显示于首个组件下方
Hey, let's break down why this is happening and how to fix it!
The core issue here is that all your MultiSelect components are sharing the single selected state variable. Whenever you make a selection in any of the dropdowns, you're updating that one state array, and every display area below is reading from the same array—so they all show the exact same content, no matter which dropdown you interact with.
Looking at your code:
- You've declared one state:
const [selected, setSelected] = useState([]); - Every MultiSelect is bound to this
selectedstate, and everyonChangehandler callssetSelectedto update this single array - All the display cells below are rendering this same
selectedarray
Naturally, any change to any dropdown overwrites the shared state, and all displays reflect that single value.
You need to track selections independently for each column. The easiest way to do this is to use an object as your state, where each key represents a unique column identifier, and the value is the selected options for that column.
Here's how to adjust your code:
- Update your state to an object to hold per-column selections:
const [selectedPerColumn, setSelectedPerColumn] = useState({});
- Add a unique identifier to each column (like a column name or ID) and use it to bind the MultiSelect to its own state slice:
// Let's say your columns have unique keys like "name", "age", "role" <MultiSelect value={selectedPerColumn[columnKey] || []} onChange={(newSelections) => { setSelectedPerColumn(prevState => ({ ...prevState, [columnKey]: newSelections })); }} options={yourOptions} />
- Render the correct selections for each column in the display area:
<td> {selectedPerColumn[columnKey]?.join(', ') || 'No selections made'} </td>
Also, make sure you're assigning a unique key prop to each table column and row when rendering—this helps React keep track of which component corresponds to which state, preventing unintended component reuse that could cause state mismatches.
内容的提问来源于stack exchange,提问作者CourtneyJ

