繁体   English   中英

在 JSX 中的条件语句中的 SetState 反应原生?

[英]SetState in a Conditional statement inside JSX in react native?

我想在 JSX 表达式中设置我的 state 并在条件为真时显示我的组件。 我试过这个:

 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> ); }

我的Item组件是:

 export default class Item extends PureComponent { render() { const { active, name, } = this.props; return ( <View style={styles.container}> <Text style={active? [styles.text, styles.active]: styles.text}>{name}</Text> </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.]

我现在得到的结果: 当前结果

我想要达到的结果是: 最后结果

您不能像这样在组件内部操作 state ,每当 state 更改组件时,都会重新渲染,因此它只会陷入无限重新渲染,

我建议在项目组件中调用 useEffect 并将月份作为道具传递。

useEffect 将可以在每次更改月份时运行代码

 useEffect(() => { if (month) { //do something here } }, [month])

尝试这样的事情。

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

对于项目组件

 <Item currentMonth={currentMonth} updateCurrentMonth={() => { setCurrentMonth(month) }} name={currentMonth?== month: getMonthFromString(month) : ""} active />

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

因为您的项目组件是 class

 componentWillMount() { this.props.updateCurrentMonth() }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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