簡體   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