【问题标题】:React Native update state in FlatList在 FlatList 中 React Native 更新状态
【发布时间】:2019-01-26 20:43:30
【问题描述】:

我正在使用 React Native 构建一个电子商务应用程序。我遇到了一个问题。在“购物篮”页面中,我想显示商品的总价。

我在开始时将状态 totalPrice 设置为 0,当我在平面列表中显示每个项目时,我想更新 totalPrice (totalPrice = totalPrice + 项目价格 * 数量)

我的代码:

class Basket extends Component {

  constructor(props) {
      super(props);
      this.state = {
        isLoading: true,
        totalPrice: 0,
      }
    }

  componentDidMount(){

    return fetch(...)
      .then((response) => response.json())
      .then((responseJson) => {

        this.setState({
          isLoading: false,
          dataSource: responseJson.records,
        }, function(){

        });

      })
      .catch((error) =>{
        console.error(error);
      });
  }

  render() {

    if(this.state.isLoading){
      return(
        <View>
          <ActivityIndicator/>
        </View>
      )
    }



    return (
      <View style={{ flex: 1}}>

        <ScrollView>

            <FlatList
              data={this.state.dataSource}
              numColumns={1}
              renderItem={({item}) => //displaying the items

              //below i want to update totalPrice but it didn't work
              
              this.setState({
                 totalPrice : this.state.totalPrice + item.quantity * 
                 item.price,
           });  
            }
            />

          </ScrollView>
            
            <View>
            <Text> {this.state.totalPrice} </Text>
            </View>


      </View>

    );

  }
}

【问题讨论】:

    标签: reactjs react-native reactive-programming expo mobile-development


    【解决方案1】:

    不要在你的组件中使用 setState。如果你想得到 totalPrice,你可以这样做:

        render() {   
        const totalPrice =
        this.state.dataSource &&
         this.state.dataSource.map((item)=> item.quantity).reduce((prev, next) => prev + next)
    
        return(
        ...
         <Text> {totalPrice} </Text>
        )
    }
    

    这里我们使用“reduce” ES6 语法。希望对你有帮助

    【讨论】:

    • 谢谢,我找到了另一个解决方案,但你的更好
    【解决方案2】:

    renderItem 中,您需要返回一个组件而不是函数。

    你的renderItem应该是这样的

    renderItem = ({ item }) => {
     return(
        <TouchableOpacity onPress={() => this.setState({
                 totalPrice : this.state.totalPrice + item.quantity * 
                 item.price,
           })}>
           <Text>Your View stays here </Text>
        </TouchableOpacity>
      );
    }
    
    <FlatList
      data={this.state.data}
      renderItem={this.renderItem}
     />
    

    我向你保证,你有一个这样的数据数组

    [{ quantity: 2, price: 22 }, { quantity: 1, price: 12 }] 而且我看到您无缘无故地将您的FlatList 包裹在ScrollView 中。首先初始化您的状态是一个好习惯。您最初可以将数据或数据源变量设置为状态内的空数组

    state = { data: [], ... }

    【讨论】:

      猜你喜欢
      • 2018-08-02
      • 1970-01-01
      • 2019-11-28
      • 2020-04-29
      • 2018-12-27
      • 2023-02-11
      • 1970-01-01
      • 2018-11-10
      • 2022-01-22
      相关资源
      最近更新 更多