[英]Conditional statement inside JSX in react native?
我想在 JSX 表達式中設置我的 state 並在條件為真時顯示我的組件。 我怎樣才能做到這一點? 我首先嘗試了這個:
{(currenMonth !== item.orderDate)
&& (setCurrentMonth(item.orderDate) && <Item name={getMonthFromString(item.orderDate)} active />)
}
在第二個解決方案中,我創建了這個 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>
);
}
但我收到一個錯誤[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.]
有兩種方式:實際上是你在 JSX 中執行的方式,然后單獨渲染 function。 我會推薦后者。 但提到, render
不是設置 state 的一部分。 所以你實際上有兩個不同的問題。
...
const renderMonthItem = () => (
(<yourConditionals> ? <Item ... /> : null;
)
...
return (
<View> ...
{ renderMonthItem() }
... </View>
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.