React Dropdown首次渲染后失效:选中项消失且二次渲染报错
Hey there! As a React newbie, it’s totally normal to run into these state-related hiccups. Let’s break down what’s causing your Dropdown’s selected value to disappear and that confusing commitRoot error.
The Core Issue: State Management Misstep
Looking at your code, you’re using PlanSelector.selectedName as the selectedKey for your Dropdown. This looks like a global or static variable—React components rely on internal state or props to track dynamic values, not global variables. When you click the button to show the form, something is probably resetting or changing that global value, and since React isn’t tracking it properly, the Dropdown loses its selected state. That inconsistent state is also likely triggering the commitRoot error (this is part of React’s final rendering phase, and errors here usually come from mismatched or invalid state during updates).
Step-by-Step Fix
Let’s switch to using component-level state to manage the selected value—this will keep everything consistent and tracked by React:
Initialize state in your component
Add a constructor (or use a class property if you prefer) to set up your initial state:constructor(props) { super(props); this.state = { selectedName: '' // Start with empty, or a default option key }; // Bind your onChange handler to the component instance this.selectedNameChanged = this.selectedNameChanged.bind(this); }Update the onChange handler to modify state
Instead of updating a global variable, usesetStateto update the component’s internal state:selectedNameChanged(value) { this.setState({ selectedName: value }); }Link the Dropdown to your component state
Change theselectedKeyprop to usethis.state.selectedNameinstead of the global variable:render() { return ( <Dropdown className='titlebar__dropdown' options={this.myOptions} onChange={this.selectedNameChanged} selectedKey={this.state.selectedName} placeholder='Select a Plan' /> ) }
Why This Fixes the Error
By using React’s built-in state management:
- React will automatically re-render the Dropdown whenever
selectedNamechanges, keeping the UI in sync. - The
commitRooterror should disappear because we’re no longer dealing with untracked global state that can change unexpectedly during renders.
Bonus Checks
- If you need to share this selected value with the form or other components, pass it as a prop instead of using a global variable. For cross-component state sharing later on, you can look into Context API or Redux, but start with component state first to keep things simple.
- Double-check your form’s pre-fill logic—make sure it’s reading the selected value from the component’s state (or props) instead of modifying a global variable that the Dropdown depends on.
内容的提问来源于stack exchange,提问作者faranak777

