通过 getParam 将项目添加到 Flatlist

Adding item to Flatlist by getParam

饮食(主页)

export class Diet extends Component {
  constructor(props) {
    super(props);
    this.state = {
       foodList: [],
             };
     }

      render() {

          return (

               <View style={{ flex: 1, top: hp("12%"), height: hp("100%") }}>
                <Button onPress={()=> this.props.navigation.navigate('FoodCreate')}>
                   <Text>Press to insert Food Name</Text>
                </Button>
                  <FlatList
                    data={{this.props.route?.params?.foodList}
                    keyExtractor={(item, index) => item.key.toString()}
                    renderItem={(data) => (
                      <ListItem itemDivider title={data.item.food} />
                    )}
                  />
                </View>

创建食物

export class FoodCreate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      food: null,
      foodList: [],
    };
  }

  submitFood = (food) => {
    this.setState({
      foodList: [
        ...this.state.foodList,
        {
          key: Math.random(),
          name: food,
        },
      ],
    });
    this.props.navigation.navigate("Diet", {
      foodList: this.state.foodList,
    });
  };
render() {
    return (
      <Container>
        <Header>
          <Left>
            <Button transparent>
              <Icon
                name="arrow-back"
                onPress={() => this.props.navigation.goBack()}
                style={{ fontSize: 25, color: "red" }}
              />
            </Button>
          </Left>
          <Body>
            <Title>Add Food</Title>
          </Body>
          <Right>
            <Button transparent>
              <Icon
                name="checkmark"
                style={{ fontSize: 25, color: "red" }}
                onPress={() => {
                  this.submitFood(this.state.food);<-----------
                }}
              />
            </Button>
          </Right>
        </Header>
        <View style={{ alignItems: "center", top: hp("3%") }}>
          <TextInput
            placeholder="Food Name"
            placeholderTextColor="white"
            style={styles.inptFood}
            value={this.state.food}
            onChangeText={(food) => this.setState({ food })}
          />
        </View>

大家好,这个应用程序应该是这样工作的:当我启动 Expo 时,它会将我带到 Diet 屏幕,然后我从那里按 Button 将新食物添加到Flatlist,一旦我被发送到 FoodCreate 屏幕,我在 TextInput 中输入食物的名称,当我点击 header 中的复选标记时,它应该将我发送回 Diet 并在 Flatlist 中显示我输入的食物名称,等等。当我 运行 应用程序时,它会给我以下错误:this.props.navigation.getParam is not a function

你必须使用

this.props.route.params.foodList

参数通过 route.params 属性传递,Navigation v5 没有 getParams 选项