【问题标题】:How can I use a state in a FlatList?如何在 FlatList 中使用状态?
【发布时间】:2019-04-27 00:47:15
【问题描述】:

我有一个FlatList,我想显示一个类似quantityproduct 的数字。所以我为此使用state。现在,当我按下 TouchableOpacity 将数量更改为 1 时,在控制台中工作正常,但在 FlatList 中看不到任何变化。

  constructor(props){
    super(props);
    this.state={
      quantity : 0,
    }

增量数量:

incrementCount=()=>{

    if(this.state.quantity != 10){
      console.log(this.state.quantity);
     this.setState((prevState, props) => ({
        quantity: this.state.quantity + 1,
      }));
    }
}

平面列表:

<FlatList
          data={this.state.dataSource}
          renderItem={({item}) =>

          <View>
            <Text>{item.title}</Text>

            <Text>{this.state.quantity}</Text>                            
            <TouchableOpacity onPress={this.incrementCount} activeOpacity={0.5}>
               <AntDesign name="plus" size={15}/>
            </TouchableOpacity>

          </View>
      }
    />

【问题讨论】:

  • 你的状态没有this.state.dataSource,ListView的数据是未定义的
  • @Vencovsky 对不起..我删除了很多代码...问题不在于那个。我认为当我们在 listView 中使用状态时我们无法更改状态。
  • 也许这会改变一些事情this.setState((prevState, props) =&gt; ({ quantity: prevState.quantity + 1, }))
  • @Vencovsky 不工作...

标签: react-native react-native-flatlist


【解决方案1】:

Listview 已弃用,现在使用 Flatlist 代替。

更多信息请参考此官方文档react-native listview

【讨论】:

  • 我现在使用 flatList 而不是在 flatList 中工作。
【解决方案2】:

这是 javascript 中 pre-incrementpost-increment 的常见问题(您可以在此处阅读更多信息:++someVariable Vs. someVariable++ in Javascript

你可以通过简单地在 setState 之前增加变量来解决这个问题:

const quantity = this.state.quantity + 1;
this.setState({ quantity }) // this is ES6 syntax

无论如何,您不应该使用 ListView,因为它已被弃用。 (https://facebook.github.io/react-native/docs/listview.html) 还有其他组件:

【讨论】:

  • 没有什么不同。我的代码工作正常,但在 listView 中不行。我认为我应该使用其他组件。
  • 我现在使用 flatList 而不是在 flatList 中工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 2020-06-20
  • 2018-08-02
  • 2020-04-29
  • 1970-01-01
相关资源
最近更新 更多