每当我单击一个开关时,我都需要创建一个新对象,并在关闭时将其删除

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了每当我单击一个开关时,我都需要创建一个新对象,并在关闭时将其删除相关的知识,希望对你有一定的参考价值。

TLDR:我需要根据打开/关闭时的选择创建一个新对象,如果我单击,则将特定项目项克隆到该新对象,依此类推,等等)>

也在reddit上也回答了这个问题-> https://www.reddit.com/r/reactnative/comments/gpvnhv/need_help_creating_a_new_object_based_on_dropdown/

编辑:我设法仅通过接收客户端来过滤下拉组件的对象,还获得了项目的过滤器以显示在平面列表中。我需要通过连接两者来寻求帮助,这意味着从下拉列表中选择一个客户端,并显示所有具有相同ID的项目,例如[]

客户列表:

[
  {
    client: 'Microsoft', 
    idClient: '1'
  },
  {
    client: 'Google', 
    idClient: '0'
  }
]

项目列表:

[
  {
    project: 'Random stuff', 
    idClient: '1'
  }, 
  {
    project: 'Another Random stuff', 
    idClient: '1'
  }, 
  {
    project: 'GG', 
    idClient: '0'
  }
]

我一直很头疼,想弄清楚这一点,我有一个带有项目/客户的对象,像这样。

items = [
 {
  client: 'Microsoft',
  idClient: 0,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'React Native App'
 },
 {
  client: 'Amazon',
  idClient: 1,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'ServerSide OPS'
 },
 {
  client: 'Microsoft',
  idClient: 0,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'AI Enhancer'
 },
 {
  client: 'Google',
  idClient: 4,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'Whatever Come Up With'
 },
 {
  client: 'KFC',
  idClient: 3,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'QR Reader'
 },     
]

这只是我的对象的示例,它有20多个客户,其中一些客户每个可以有大约3或4个项目,整个对象大约有60到70个项目。

我有两个屏幕,其中一个是主屏幕,每天渲染一个带有自定义视图的日历条,好的,这里是有趣的部分,这是我的问题出处]]

[第二个屏幕是一个下拉菜单,我在其中选择一个客户端,并根据所选的客户端列出我的所有项目,最大的问题是,因为我无法操纵该对象,所以首先,我需要为每个项目进行切换,以便选择我需要在第一个屏幕上显示的对象,其次,该新对象需要包含(除了对象中的项目之外)更多的东西,例如{项目:“ React Native App”,hoursRemaining :10,等等...}

这里是下拉列表屏幕的完整代码

import * as React from 'react';
import {View, Text, Image, StatusBar, SafeAreaView, TouchableOpacity, ScrollView, RefreshControl, FlatList, Platform} from 'react-native';
import { Header, ListItem } from 'react-native-elements';
import ModalDropdown from 'react-native-modal-dropdown';
import Images from '../../Assets/values/images';
import { RFPercentage as rfp, RFValue as rfv } from 'react-native-responsive-fontsize';
import { heightPercentageToDP as hp, widthPercentageToDP as wp } from 'react-native-responsive-screen';
import styles from '../../Assets/values/styles/HoursReport/ClientsProyects/ClientsProyectsStyle';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import DataManager from '../../../Util/CrossUtils/DataManager';

export default class ClientsProyectsScreen extends React.Component<any, any> {
  constructor(props: any) {
    super(props);

    this.state = {
      SeleccionClientes: '',
    }
  }

    items = [
 {
  client: 'Microsoft',
  idClient: 0,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'React Native App'
 },
 {
  client: 'Amazon',
  idClient: 1,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'ServerSide OPS'
 },
 {
  client: 'Microsoft',
  idClient: 0,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'AI Enhancer'
 },
 {
  client: 'Google',
  idClient: 4,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'Whatever Come Up With'
 },
 {
  client: 'KFC',
  idClient: 3,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'QR Reader'
 },     
]

  componentDidMount(){
    console.log(DataManager.ResponseProjectClient);
  }

  searchCliente = item => {
    var jsonData = item;
    var searchData = [];
    jsonData.forEach(element => {
      searchData.push(element.cliente);
    });
    return searchData;
  }

  searchProyecto = item => {

  }

  updateFav = item => {
   const newData = [...this.items[this.state.SeleccionClientes]];
   const updateItem = newData.find(x => x.key === item.key);
   updateItem.fav = !item.fav;
   const updatedArray = Object.assign(this.items);
   updatedArray[this.state.SeleccionClientes] = newData;
   this.setState({ items: updatedArray });
  };

  render() {
    return (
      <>
        <StatusBar translucent backgroundColor="transparent" />
        <SafeAreaView style={{backgroundColor: '#fafafa'}}/>
        {/*
        <Header
          backgroundImage={Images.header_nav}
          backgroundImageStyle={styles.HeaderImagenCP}
          leftComponent={
            <TouchableOpacity onPress={() => this.props.navigation.goBack()}>
              <View><Image style={styles.HeaderHorizontal} source={Images.back}/></View>
            </TouchableOpacity>
          }
          centerComponent={{text: 'Imputar horas', ellipsizeMode: 'clip', style: styles.HeaderHoursReportCP }}
          placement='center'
        />
        */}
        <View style={styles.ContainerBackground}>
        <View style={{flexDirection: 'row'}}>
          <View style={{alignItems: 'flex-start', justifyContent: 'flex-start', alignSelf: 'flex-start', marginTop: hp('2.2%'), marginLeft: wp('6.3%')}}>
            <Text style={{
              fontSize: rfv(18),
              fontWeight: "500",
              fontStyle: "normal",
              textAlign: "left",
              color: "#707070"
            }}>Proyectos</Text>
          </View>
          <TouchableOpacity style={{position: 'absolute', alignItems: 'flex-end', justifyContent: 'flex-end', alignSelf: 'flex-end', paddingBottom: hp('1%'), left: wp('90%')}} onPress={() => this.props.navigation.goBack()}>
            <Image source={Images.close_modal}/>
          </TouchableOpacity>
        </View>
        <KeyboardAwareScrollView
          keyboardShouldPersistTaps="handled"
          enableOnandroid={true}>
            {/*
            <View style={{alignItems: 'flex-end', justifyContent: 'flex-end', alignSelf: 'flex-end', marginRight: widthPercentageToDP('6.3%')}}>
              <TouchableOpacity onPress={() => this.props.navigation.goBack()}>
                <Image source={Images.close_modal}/>
              </TouchableOpacity>
            </View>
            */}
            <View style={styles.Left}>
              <Text style={styles.TituloInputOnBlur}>Cliente</Text>
            </View>
            <View style={styles.Center}>
              <ModalDropdown
                adjustFrame={style => {
                  style.top =(Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
                  return style;
                }}
                dropdownTextStyle={styles.dropdownTextStyle}
                dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
                dropdownStyle={styles.dropdownStyle}
                defaultValue={'Seleccionar'}
                style={styles.dropStyle}
                textStyle={{
                  padding: 0,
                  margin: 0,
                  fontSize: rfv(16),
                  paddingVertical: hp('1.2%'),
                  fontWeight: 'normal',
                  fontStyle: 'normal',
                  textAlign: 'left',
                }}
                //onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                //options={Object.keys(this.state.items)}
                onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                options={Object.keys(this.items)}
              />
            </View>
            <View>
            {
              this.items[this.state.SeleccionClientes] != null ?
              <View>
                {
                  <FlatList
                    data={this.items[this.state.SeleccionClientes]}
                    renderItem={({item, index}) => (
                      <ListItem
                        containerStyle={{backgroundColor: '#fafafa', width: wp('87.1%'), height: 64, alignItems: 'center', justifyContent: 'center', alignSelf: 'center', marginTop: hp('2.8%'), paddingHorizontal: 0}}
                        topDivider={false}
                        bottomDivider={true}
                        titleStyle={{
                          marginLeft: 0,
                          fontSize: rfv(16),
                          fontWeight: "normal",
                          fontStyle: "normal",
                          textAlign: "left",
                          color: "#707070"
                        }}
                        subtitleStyle={{
                          marginLeft: 0,
                          fontSize: rfv(14),
                          fontWeight: "normal",
                          fontStyle: "normal",
                          textAlign: "left",
                          color: "#c4c4c4"
                        }}
                        title={`${item.name}`}
                        subtitle={`ID ${item.key}`}
                        switch={{
                          trackColor: { false: "#767577", true: "#81b0ff" },
                          thumbColor: item.fav == true ? "#1062cc" : "#f4f3f4",
                          ios_backgroundColor: "#9e9e9e",
                          value: item.fav, 
                          onValueChange: () => this.updateFav(item)
                        }}
                      />
                    )}
                  />
                }
              </View>
              :
              <View style={{alignItems: 'center', justifyContent: 'center', alignSelf: 'center'}}>
                <View style={{marginTop: hp('11%')}}>
                  <Image style={{marginBottom: hp('2.8%')}} source={Images.sad_face}/>
                </View>
                <Text style={{
                  fontSize: rfv(18),
                  fontWeight: "normal",
                  fontStyle: "normal",
                  textAlign: "left",
                  color: "#c4c4c4"
                }}>Sin proyectos activos</Text>
              </View>
            }
            </View>
          <View style={styles.BottomPush} />
        </KeyboardAwareScrollView>
        </View>
      </>
    );
  }
}

TLDR:我需要根据打开/关闭时的选择创建一个新对象,如果我单击,则将特定项目项克隆到该新对象,依此类推,在reddit上也有此问题->。 ..

为了解决此问题,您需要在API responseown data之间进行抽象,可以对其进行操作以添加/删除数据(即:收藏夹)。

为了使下拉菜单显示一系列客户,您可以使用帮助器功能:

const buildOptions = () => {
   return items.reduce((output, current) => {
      const { client } = current;
      output.push(client);
      return output;
}, []);
};
// returns: ['Walmart','Microsoft','Google']

[很遗憾,react-native-modal-dropdown中存在一个限制,即您无法选择idClient。因此,假设您的客户名是唯一的,则可以使用一个帮助函数,该函数从客户名返回客户ID,当用户进行选择时,会在onChange属性中触发该客户ID:

const findClientIdByName = (name) => {
   return dropItems.find(item => item.client === name).idClient;
}

现在,当用户选择一些喜欢的项目时,过滤后的列表将使用保存开关状态的特定属性(即fav: true)进行更新。就是说,最初,fav属性为undefined,这意味着开关将自动为“ OFF”。

然后,您可以创建一个返回喜欢的项目的函数:

const favoriteProjects = list.filter(item => item.fav);

最后,在日历视图中,您可以像这样构建最终对象:

  const finalObject = { [selectedDate]: favoriteProjects };
答案

为了解决此问题,您需要在API responseown data之间进行抽象,可以对其进行操作以添加/删除数据(即:收藏夹)。

以上是关于每当我单击一个开关时,我都需要创建一个新对象,并在关闭时将其删除的主要内容,如果未能解决你的问题,请参考以下文章

为所有对象创建一个委托,而不是为每个对象创建一个委托

IBM Worklight 中的登录认证

Android:我画了很多形状。每当我单击它时,我都需要更改形状的颜色

Activity 完成时更新 ListFragment

数据库迁移:单个创建脚本与更改集

每当单击按钮时如何重置计时器