[英]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.我想在 JSX 表达式中设置我的 state 并在条件为真时显示我的组件。 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:在第二个解决方案中,我创建了这个 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.]
[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.有两种方式:实际上是你在 JSX 中执行的方式,然后单独渲染 function。 I'll recommend the latter.
我会推荐后者。 But mentioned,
render
is not part of setting state.但提到,
render
不是设置 state 的一部分。 So you actually have two separate problems.所以你实际上有两个不同的问题。
...
const renderMonthItem = () => (
(<yourConditionals> ? <Item ... /> : null;
)
...
return (
<View> ...
{ renderMonthItem() }
... </View>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.