Home > Enterprise >  When returning two components from the map function, how can we avoid duplication?
When returning two components from the map function, how can we avoid duplication?

Time:09-19

I am using React. I have an object called item.

item has three array objects called children. At this time, I run the map function on item.children and I want to run the Child component. My expectation is that if you pass props to v, LeftCon and I thought that 3 v would be delivered to each child component, but 6 v is in LeftCon, and 6 is in Child.

How can I only pass v 3 times with the same value in each component?

this is my code

 const item = {
    children: [
        { placeId: 1 },
        { placeId: 2 },
        { placeId: 3 },

    ]
}


  {item.children.map((v) => {
              return (
                <>
                  <LeftCon
                    item={v} key={v.placeId}
                    monthdates={monthdates}
                    hours={hours}
                  />

                  <Child item={v} key={v.placeId}
                    monthdates={monthdates}
                    hours={hours}
                  />

                </>
              )
            })}


   const LeftCon = ({ item }) => {

    return (

    );
};



const Child = ({ item }) => {

    return (

    );
};

CodePudding user response:

This code behaves expected:

import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';

const item = {
  children: [{ placeId: 1 }, { placeId: 2 }, { placeId: 3 }],
};

const LeftCon = ({ item }) => {
  return (
    <View>
      <Text>{item.placeId}</Text>
    </View>
  );
};

const Child = ({ item }) => {
  return (
    <View>
      <Text>{item.placeId}</Text>
    </View>
  );
};

export default function App() {
  return (
    <View style={styles.container}>
      {item.children.map((v) => {
        return (
          <>
            <LeftCon
              item={v}
              key={v.placeId}
            />

            <Child
              item={v}
              key={v.placeId}
            />
          </>
        );
      })}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

Each component Child and LeftIcon were called three times.

  • Related