简体   繁体   English

如何将 1d 转换为 2d 并将其存储在 react native state 中?

[英]How to convert 1d into 2d and store it in a react native state?

I have an array,我有一个数组,

const array = [
{"row":"0", "column": "0"}, 
{"row":"0", "column": "1"},
{"row":"1", "column": "0"},
{"row":"1", "column": "1"}, 
{"row":"2", "column": "0"}, 
{"row":"2", "column": "1"}
]

Note: the rows and columns arent predefined, it may change every time.注意:行和列不是预定义的,每次都可能改变。

From the array i need to create a 2D array and store it on a state in react native, so that i can use the state to render the requirements using the array stored,从数组中我需要创建一个二维数组并将其存储在 state 中以 react native,这样我就可以使用 state 来使用存储的数组呈现需求,

I have two problems, one is converting 1d into 2d and another one is storing it into an state for further usage,我有两个问题,一个是将 1d 转换为 2d,另一个是将其存储到 state 中以供进一步使用,

My 1d to 2d converting function:我的 1d 到 2d 转换 function:

for (let i = 0; i < this.state.array.length; i++) {
       let row = this.state.array[i].row;
            if (newSeats[row] === undefined) newSeats[row] = [];
               newSeats[row].push(this.state.array[i]);
       }

for (let i = 0; i < this.state.array.length; i++) {
       let column = this.state.array[i].column;
             if (newSeatss[column] === undefined) newSeatss[column] = [];
               newSeatss[column].push(this.state.array[i]);
       }

It gives two arrays, so is this efficient way to convert 1d to 2d?它给出了两个 arrays,那么这种将 1d 转换为 2d 的有效方法吗? And i cant use setstate here as it throws error saying maximum depth reached for setstate, So how to store the result in a state?我不能在这里使用 setstate,因为它会抛出错误,说明 setstate 达到了最大深度,那么如何将结果存储在 state 中? and if there is any other better way make the conversion please suggest !如果有任何其他更好的方法进行转换,请提出建议!

And my whole component:我的整个组成部分:

import React, { Component} from 'react';
import { View, Text, StyleSheet, ScrollView, Dimensions, TouchableOpacity, FlatList } from 'react-native';
import { connect } from 'react-redux';
import { fetchSeatLayout } from '../../actions/HomeActions';
import Loader from '../components/loader';
import { Feather } from '@expo/vector-icons';
import { Button } from 'react-native-elements';

const w = Dimensions.get('window').width;
const h = Dimensions.get('window').height;

class SeatLayout extends Component {

    state = { isLoading: true, selectedSeatLayouts: [], seatArray: [] }

    componentDidMount() {
        this.props.fetchSeatLayout(this.props.selectedBus.id, (data) => {
            this.setState({ isLoading : false, selectedSeatLayouts: data.seats })
        }) 
       
    }
   

    seats = () => {

        let arr2d = this.state.selectedSeatLayouts.reduce((r, {column, row, name }) => {
            if (!r[row]) r[row] = [];
            r[row][column] = name;
            return r;
        }, []);
          console.log(arr2d);
  
    }


    render() {
        
        return(
            <View style={styles.container}>
                <Loader
                    loading={this.state.isLoading} />

                <View style={{ flex: 1 }}>
                    <View style={styles.headerContainer}>
                        <View style={{ paddingTop: 50, paddingHorizontal: 20, alignItems: 'center' }}>
                            <Text>30 Sep, 2020</Text>
                        </View>
                    </View>
                    
                    <View style={styles.bodyContainer}>
                           {this.seats()}    
                    </View>
                </View>
            
            

            </View>
        )
    }
}


const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff'
    },
    headerContainer:{
        height: h * 0.23,
        backgroundColor: '#f0eff4',
    },
    bodyContainer:{
        justifyContent: 'center'
        
    },
});


const mapStateToProps = state => {
    return {
        selectedBus: state.home.userSelectedBus,
    }
}

export default connect(mapStateToProps, {fetchSeatLayout})(SeatLayout);

Update your componentDidMount to this, so it saves the 2D array in the state将您的 componentDidMount 更新为此,以便将二维数组保存在 state

componentDidMount() {
  this.props.fetchSeatLayout(this.props.selectedBus.id, (data) => {
    this.setState({ isLoading : false, selectedSeatLayouts: data.seats},()=>{
      this.setState({seatArray:this.seats()})
    })
  }) 
}

Right now seats function isn't returning anything, please update it to return something现在seats function 没有返回任何东西,请更新它以返回一些东西

seats = () => {
  let arr2d = this.state.selectedSeatLayouts.reduce((r, {column, row, name }) => {
      if (!r[row]) r[row] = [];
      r[row][column] = name;
      return r;
  }, []);
    console.log(arr2d);
  return arr2d;
}

At this point you have a state with a parameter seatArray, you can use it as per your requirement now.此时您有一个带有参数 seatArray 的 state,您现在可以根据需要使用它。

Update this code block to show something instead of calling 2darr,更新此代码块以显示内容而不是调用 2darr,

<View style={styles.bodyContainer}>
  {this.seats()} //remove this to show some visual component   
</View>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM