在FlatList中反应本机更新状态

时间:2019-01-26 20:43:30

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

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

我在开始时将状态totalPrice设置为0,并且当我在平面列表中显示每个项目时,我想更新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>

    );

  }
}

2 个答案:

答案 0 :(得分:3)

不要在组件内部使用setState。如果要获取totalPrice,可以执行以下操作:

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

    return(
    ...
     <Text> {totalPrice} </Text>
    )
}

这里我们使用“减少” ES6语法。希望对您有帮助

答案 1 :(得分:0)

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中。最好先初始化您的状态。您可以最初将data或datasource变量设置为状态内的空数组

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

相关问题