简体   繁体   中英

React Native : Modify Component Level State with FlatList

I have two sections inside my main component. One section holds a FlatList and the other one displays the summation of a value in the object that FlatList receives. My main components looks like so:

return (
  <View>
  <FlatList
    data={[{a:1,b:2},{a:3,b:4}]}
    renderItem={({item})=><View>{item.a}</View>}
  />
  <View>**SUM OF a(i.e 1+3=4)**</View>
  </View>
)

I am not able to display the summation of all a inside my second view. When I try to modify the internal state of the app using this.setState({a: this.state.a + item.a}) inside renderItem , I get an error.

The other way that I thought would be helpful is by looping through the object and not using FlatList at all. But even in that case, I am not able to use this.setState({a: this.state.a + item.a}) from within the vanilla javascript's map function.

Example:

const arr = [{a:1,b:2},{a:3,b:4}]
arr.map(e=>{
  return this.setState({a: this.state.a + e.a})
})

What am I doing wrong?

EDIT: I realized you are trying to sum all of the a elements instead of modifying all the a elements in an array.

You cannot use setState the way you are trying to in your map . First of all, you should never invoke it in a render method. You are causing a rerender every time you call setState which is likely causing the error.

To sum the a properties do something like this:

sumA(newArray) {
  const newA = newArray.reduce((a, b) => a + b, this.state.a || 0 )

  this.setState({ a: newA });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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