Javascript 使用useState钩子基于Web Api添加状态以动态响应本机

Javascript 使用useState钩子基于Web Api添加状态以动态响应本机,javascript,reactjs,react-native,ecmascript-6,Javascript,Reactjs,React Native,Ecmascript 6,我有以下问题: 我打算通过web API获取数据,在此基础上,React Native将使用FlatList呈现数据。在本例中,它将使用子组件(复选框)。因此,将有多个支票盒 当我不知道这些复选框的计数时,如何创建和更新它们的状态,然后将它们的状态传递给子组件 const data = [{ id:0, product:"A" price:30 }, { id:1, product:"B" price:20 }, {

我有以下问题:

我打算通过web API获取数据,在此基础上,React Native将使用FlatList呈现数据。在本例中,它将使用子组件(复选框)。因此,将有多个支票盒

当我不知道这些复选框的计数时,如何创建和更新它们的状态,然后将它们的状态传递给子组件

const data = [{
   id:0,
   product:"A"
   price:30
},
{
   id:1,
   product:"B"
   price:20
},
{
   id:1,
   product:"C"
   price:10
}]

(我在挠头)

输出:

下面是一个应用程序的工作示例,它显示了数据选择和数据流到下一个屏幕,实现数据获取,并相应地执行服务器端

import React, { useState, useEffect } from 'react';
import {
  Text,
  View,
  StyleSheet,
  FlatList,
  CheckBox,
  Button,
  Modal,
} from 'react-native';
import Constants from 'expo-constants';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

const data = [
  {
    id: 0,
    product: 'A',
    price: 30,
    selected: false,
  },
  {
    id: 2,
    product: 'B',
    price: 20,
    selected: false,
  },
  {
    id: 3,
    product: 'C',
    price: 10,
    selected: false,
  },
];

const Stack = createStackNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Payment" component={PaymentScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

function PaymentScreen({ navigation, route }) {
  const { selected } = route.params;
  return (
    <FlatList
      data={selected}
      renderItem={({ item }) => (
        <Card style={{ margin: 5 }}>
          <View style={styles.card}>
            <View
              style={{
                flexDirection: 'row',
                width: 50,
                justifyContent: 'space-between',
              }}>
              <Text>{item.product}</Text>
            </View>
            <Text>{item.price} USD</Text>
          </View>
        </Card>
      )}
    />
  );
}

function HomeScreen({ navigation }) {
  const [products, setProducts] = useState(data);
  const [showModal, setShowModal] = useState(false);
  const [selected, setSelected] = useState([]);

  const handleChange = (id) => {
    let temp = products.map((product) => {
      if (id === product.id) {
        return { ...product, selected: !product.selected };
      }
      return product;
    });
    setProducts(temp);
  };

  const getSelected = () => {
    let temp = products.filter((product) => product.selected);
    setSelected(products.filter((product) => product.selected));
    console.log(temp);
  };

  useEffect(() => {
    getSelected();
  }, [showModal]);

  return (
    <View style={styles.container}>
      <Modal animationType="slide" transparent={true} visible={showModal}>
        <View style={styles.modalView}>
          <FlatList
            data={selected}
            renderItem={({ item }) => (
              <Card style={{ margin: 5 }}>
                <View style={styles.card}>
                  <View
                    style={{
                      flexDirection: 'row',
                      width: 50,
                      justifyContent: 'space-between',
                    }}>
                    <Text>{item.product}</Text>
                  </View>
                  <Text>{item.price} USD</Text>
                </View>
              </Card>
            )}
          />
          <Text>
            Total :{' '}
            {selected.reduce((acc, curr) => acc + curr.price, 0).toString()}
          </Text>
          <Button
            title={'BUY'}
            onPress={
              selected
                ? () => {
                    setShowModal(false);
                    navigation.navigate('Payment', { selected: selected });
                  }
                : setShowModal(false)
            }
          />
        </View>
      </Modal>
      <FlatList
        data={products}
        renderItem={({ item }) => (
          <Card style={{ margin: 5 }}>
            <View style={styles.card}>
              <View
                style={{
                  flexDirection: 'row',
                  width: 50,
                  justifyContent: 'space-between',
                }}>
                <CheckBox
                  value={item.selected}
                  onChange={() => {
                    handleChange(item.id);
                  }}
                />
                <Text>{item.product}</Text>
              </View>
              <Text>{item.price} USD</Text>
            </View>
          </Card>
        )}
      />
      <Button
        title={'ADD TO CART'}
        onPress={() => {
          setShowModal(true);
          console.log(showModal);
        }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },

  card: {
    padding: 10,
    margin: 5,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  modalView: {
    margin: 20,
    backgroundColor: 'white',
    borderRadius: 20,
    padding: 5,
    justifyContent: 'space-between',
    alignItems: 'center',
    elevation: 5,
  },
});
import React,{useState,useffect}来自“React”;
进口{
文本,
看法
样式表,
平面列表,
复选框,
按钮
情态动词
}从“反应本机”;
从“expo常量”导入常量;
从'@react-navigation/native'导入{NavigationContainer};
从'@react navigation/stack'导入{createStackNavigator};
//可以从本地文件导入
从“./components/AssetExample”导入AssetExample;
//或npm中可用的任何纯javascript模块
从“react native paper”导入{Card};
常数数据=[
{
id:0,
产品:"A",,
价格:30,,
选择:false,
},
{
id:2,
产品:"B",,
价格:20,,
选择:false,
},
{
id:3,
产品:"C",,
价格:10,,
选择:false,
},
];
const Stack=createStackNavigator();
导出默认函数App(){
返回(
);
}
功能付款屏幕({导航,路线}){
const{selected}=route.params;
返回(
(
{item.product}
{项目价格}美元
)}
/>
);
}
功能主屏幕({navigation}){
const[products,setProducts]=使用状态(数据);
const[showmodel,setshowmodel]=useState(false);
const[selected,setSelected]=useState([]);
常量handleChange=(id)=>{
让temp=products.map((产品)=>{
if(id==product.id){
返回{…产品,所选:!product.selected};
}
退货产品;
});
设定产品(温度);
};
常量getSelected=()=>{
设温度=products.filter((product)=>product.selected);
setSelected(products.filter((product)=>product.selected));
控制台日志(temp);
};
useffect(()=>{
getSelected();
},[showModal]);
返回(
(
{item.product}
{项目价格}美元
)}
/>
总计:{'}
{selected.reduce((acc,curr)=>acc+curr.price,0).toString()}
{
设置显示模式(假);
导航('Payment',{selected:selected});
}
:setShowModal(假)
}
/>
(
{
handleChange(项目id);
}}
/>
{item.product}
{项目价格}美元
)}
/>
{
设置显示模式(真);
console.log(showmodel);
}}
/>
);
}
const styles=StyleSheet.create({
容器:{
弹性:1,
为内容辩护:“中心”,
paddingTop:Constants.statusBarHeight,
背景颜色:“#ecf0f1”,
填充:8,
},
卡片:{
填充:10,
差额:5,
flexDirection:'行',
justifyContent:'之间的空间',
},
莫达尔维:{
差额:20,
背景颜色:“白色”,
边界半径:20,
填充:5,
justifyContent:'之间的空间',
对齐项目:“居中”,
标高:5,
},
});

您可以在这里使用工作代码:

这是简单的逻辑代码,您必须按照需要的方式实现它

checkBoxChanged = (index) => {
       const newData = [...this.state.data];
       const newData[index].checked = !newData[index].checked;
       this.setState({data: newData});       
}

{this.state.data((item, i) => {
       return (
         <View>
          .......                                   
          <CheckBox
            ......
            checked={item.checked || false}
             onValueChange={() => this.checkBoxChanged(i)}
          />
          .......  
        </View>
})}
checkBoxChanged=(索引)=>{
const newData=[…this.state.data];
常量newData[index]。选中=!newData[index]。选中;
this.setState({data:newData});
}
{this.state.data((项目,i)=>{
返回(
.......                                   
this.checkBoxChanged(i)}
/>
.......  
})}

请发布代码,而不是问题陈述。您从API获得的数据是什么形式的?如果您没有代码,请发布UI图片并进一步解释,这样人们就可以在发布答案后给您一个具体的答案,而无需来回问题。代码可以帮助我们更好地帮助您。@KetanRamteke-我正在尝试实现这一点,因此我不需要代码。不过,我已经添加了UI设计和数据提要。问题是,提要可以更改,从3个产品更改为5个或更多……如果它们是静态的,则很容易保存状态。但在这种情况下,我如何实现这一点?很好,那么当您单击复选框时,会显示哪些应用程序行为ou是否打算实现?是否应在导航后将所选项目传递到另一个屏幕,或使用带有选中/未选中信息的变异列表更新状态?当按下/选择时,相应的产品将显示复选标记(通过将状态传递给子组件)。最后有一个“购买”按钮,该按钮将打开模式并显示所选产品和总价,用户将单击“确认”完成购买,所选产品的数据以及客户信息将发送到服务器。非常感谢您的详细回复。我觉得这非常有帮助。我将浏览并更新当然,它不会像现在这样工作,你必须根据你的项目在这里和那里做一些修改。无论如何,我希望这个答案对你有帮助,同时,愉快地编码。你的代码帮助了我