简体   繁体   中英

Conditional statement inside JSX in react native?

I want to set my state inside JSX expression and show my component if the condition is true. How can i achieve that? i tried this this first:

{(currenMonth !== item.orderDate)
                && (setCurrentMonth(item.orderDate) && <Item name={getMonthFromString(item.orderDate)} active />)
              }

In a second solution i've created this function:

const ProductsList = () => {
  const [currenMonth, setCurrenMonth] = useState('');
  const renderItem = (month) => {
        if (currenMonth !== month) {
          setCurrenMonth(month);
          return <Item name={getMonthFromString(month)} active />;
        }
        return null;
      };
  return(
   <View style={styles.container}>
     <FlatList
            data={products}
            keyExtractor={(item, index) => index.toString()}
            renderItem={({ item }) => {
              return (
                <View>
                  { renderItem(item.orderDate) }
                </View>
              );
            }}
     />
   </View>
  );
}

But i'm getting an Error [Unhandled promise rejection: Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.] [Unhandled promise rejection: Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.]

There are two ways: practically the way you're doing it inside JSX and then a separate rendering function. I'll recommend the latter. But mentioned, render is not part of setting state. So you actually have two separate problems.

...
const renderMonthItem = () => (
  (<yourConditionals> ? <Item ... /> : null;
)

...

return (
  <View> ...
    { renderMonthItem() }
  ... </View>
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM