You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native子组件更新父组件数组问题求助

React Native子组件更新父组件数组后FlatList不显示内容的问题修复

核心问题及修复步骤

1. AddMedication组件按钮点击顺序错误

当前TouchableOpacity的onPress先执行goBack再调用addMedication,会导致组件在执行添加逻辑前就被卸载,addMedication无法正确触发父组件状态更新。

修复后代码:

onPress={() => { 
  this.props.addMedication(this.state.name, this.state.dosage, 
                           this.state.selectedMeasurement, this.state.timesDaily) 
  this.props.navigation.goBack()
}}

2. MedicationList组件渲染函数未返回元素

medication函数定义了JSX但未加return,导致FlatList无内容可渲染,同时存在属性名拼写和匹配错误。

修复后代码:

medication = ({ item }) => {
  return (
    <View style={{ flexDirection: 'row' }}>
      <View style={{ width: 50, backgroundColor: 'lightyellow'}}>
          <Text style={{ fontSize: 16, fontWeight: 'bold', textAlign: 'center'}}>{item.name}</Text>
      </View>
      <View style={{ width: 400, backgroundColor: 'lightpink'}}>
          {/* 修正属性:父组件传递的是measurement而非selectedMeasurement */}
          <Text style={{ fontSize: 16, fontWeight: 'bold' , textAlign: 'center'}}>{item.dosage}{item.measurement}</Text>
      </View>
      <View style={{ width: 400, backgroundColor: 'lavender'}}>
          {/* 修正拼写:timesDaily而非timesDaiy */}
          <Text style={{ fontSize: 16, fontWeight: 'bold' , textAlign: 'center'}}>{item.timesDaily}</Text>
      </View>
    </View>
  )
}

3. FlatList缺失keyExtractor属性

FlatList需要唯一标识每个item,缺失该属性会引发警告并影响渲染稳定性。

修复后代码(添加到FlatList):

<FlatList 
  data={this.props.medications} 
  renderItem={this.medication}
  keyExtractor={(item, index) => index.toString()}
/>

4. TextInput值类型不匹配

AddMedication中dosage初始值为数字0,但TextInput的value需为字符串类型,会导致输入异常。

修复后代码:

constructor(props) {
  super(props);
  this.state = {
    dosage: '', // 改为字符串空值
    name: '',
    selectedMeasurement: "mg",
    timesDaily: '',
    prescriber: '',
    forDiagnoses: '',
    instructions: '',
    validity: false,
  };
}

setDosage = (dosage) => {
  let isValid = this.isFormValid();
  this.setState({ dosage: dosage, validity: isValid }); // 保持字符串类型
}

修复后流程验证

  1. 在AddMedication页面填写表单,点击添加按钮时先触发父组件addMedication方法,更新medications数组状态。
  2. 返回MedicationList页面后,FlatList会接收更新后的medications props,正确渲染所有药品条目。

内容的提问来源于stack exchange,提问作者tscott22

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 00:50:29