父组件状态变更后子RadioButton组件未重新渲染求助
问题分析与解决方案
问题根源
RadioButton组件内部维护了独立的isSelected状态,仅在首次渲染时使用父组件传入的props.isSelected初始化。当父组件radioGroupRefreshData更新后,子组件的内部状态不会自动同步,导致子组件无法响应父组件的数据变化。同时,子组件先修改自身状态再触发父组件回调的设计,造成了状态管理分散,容易引发数据不一致。
解决方案:改为受控组件
让RadioButton完全依赖父组件传入的状态和回调,不再维护内部状态,统一由父组件管理单选组的选中状态。
修改后的RadioGroup组件(补充key属性)
const RadioGroup = ({radioGroupData}) => { const [radioGroupRefreshData, setRadioGroupRefreshData] = useState(radioGroupData); const handleClick = (index) => { setRadioGroupRefreshData(radioGroupRefreshData.map((obj, i) => { return { text: obj.text, isSelected: i === index }; })); }; return ( <View style={styles.container}> { radioGroupRefreshData.map((obj, i) => { // 补充key属性,帮助React识别组件 return <RadioButton key={i} index={i} text={obj.text} isSelected={obj.isSelected} onClick={handleClick} /> }) } </View> ); }
修改后的RadioButton组件
const RadioButton = (props) => { const handlePress = () => { // 直接调用父组件的回调,由父组件处理选中状态 props.onClick(props.index); } return ( <TouchableOpacity style={styles.outsideContainer} onPress={handlePress}> <View style={styles.radioButtonContainer}> { props.isSelected && <RadioButtonInnerIcon width={15} height={15} fill="#04004C" /> } </View> <Text style={styles.radioButtonText}>{props.text}</Text> </TouchableOpacity> ); }
修改说明
- 移除子组件内部状态:删除RadioButton中的
isSelected状态变量、useState和useEffect逻辑,直接使用父组件传入的props.isSelected控制显示。 - 简化点击逻辑:点击时直接调用父组件的
onClick回调,将当前按钮索引传递给父组件,由父组件统一更新单选组的选中状态。 - 添加key属性:在RadioGroup的map循环中为RadioButton添加
key,确保React能正确识别组件实例,避免不必要的渲染问题。
内容的提问来源于stack exchange,提问作者Dacaramo
相关产品推荐
相关产品推荐

