Javascript react native中JSX内的条件语句?
我想在JSX表达式中设置我的状态,如果条件为true,则显示我的组件。我怎样才能做到这一点?我先试过这个:Javascript react native中JSX内的条件语句?,javascript,react-native,if-statement,Javascript,React Native,If Statement,我想在JSX表达式中设置我的状态,如果条件为true,则显示我的组件。我怎样才能做到这一点?我先试过这个: {(currenMonth !== item.orderDate) && (setCurrentMonth(item.orderDate) && <Item name={getMonthFromString(item.orderDate)} active />) } {(currenM
{(currenMonth !== item.orderDate)
&& (setCurrentMonth(item.orderDate) && <Item name={getMonthFromString(item.orderDate)} active />)
}
{(currenMonth!==item.orderDate)
&&(setCurrentMonth(item.orderDate)和&)
}
在第二个解决方案中,我创建了此函数:
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>
);
}
constproductslist=()=>{
const[currenMonth,setCurrenMonth]=使用状态(“”);
const renderItem=(月)=>{
如果(当前月份!==月份){
setCurrenMonth(月);
返回;
}
返回null;
};
返回(
index.toString()}
renderItem={({item})=>{
返回(
{renderItem(item.orderDate)}
);
}}
/>
);
}
但我收到一个错误
[未处理的承诺拒绝:不变违反:超过最大更新深度。当组件在componentWillUpdate或componentDidUpdate内重复调用setState时,可能会发生这种情况。React限制嵌套更新的数量以防止无限循环。]
有两种方法:实际上是在JSX中执行的方法,然后是单独的渲染函数。我推荐后者。但是提到,render
不是设置状态的一部分。所以你实际上有两个不同的问题
...
const renderMonthItem = () => (
(<yourConditionals> ? <Item ... /> : null;
)
...
return (
<View> ...
{ renderMonthItem() }
... </View>
);
。。。
const renderMonthItem=()=>(
(?:空;
)
...
返回(
...
{renderMonthItem()}
...
);
你不应该在条件中设置状态并检查它。创建一个单独的函数,在外部调用,然后在条件中检查状态是否为真。我编辑了我的代码,你能检查我做错了什么吗?我编辑了我的代码,你能检查我做错了什么吗?