Просмотр меню и подменю с использованием отношения родительского элемента в реактивном - PullRequest
0 голосов
/ 09 октября 2018

Я хочу показать МЕНЮ следующим образом:

Main Display example

Я использовал функцию ревизии дляреализовать это, я зашел так далеко НО ЭТО НЕ МЕНЯЕТСЯ

Вот данные из API

Data from Api

Я также пытался отобразить меню, используя карту и функцию фильтра js, но безуспешно ни в одном из них.Любая помощь будет оценена.

    import React from 'react';
            import {
               Image,ScrollView,StyleSheet,Text, View 

            } from 'react-native';

            import Panel from '../../components/BottomTabFiles/Panel';
            import {fetchRestaurantMenu} from '../actions/restaurantMenuAction';
            import {connect} from "react-redux";

            class BookmarkReservations extends React.Component{

            componentDidMount() {

              this.props.fetchRestaurantMenu("getmenu"); //calling api from redux
            }

            MainMethod(){  //This is main method that will be called
                let data = this.props.restaurantMenuDetails.restaurantMenu, 
                  //getting data from redux
                   rawList = [],
                   tempList = [],
                   self = this,
                   MainMenuArray = [];

                   data.forEach(dataItem=>{
                    rawList.push(dataItem);
                    });

      //if an item is parent, then put it into tempList(MainMenu or ParentItem has 
      //m_pid of '00000000-0000-0000-0000-000000000000')

                    rawList.forEach(function(dataItem){
                        if(dataItem.m_pid == '00000000-0000-0000-0000-000000000000')  
                         {
                          tempList.push(dataItem);
                        }           
                      });

                        MainMenuArray.push( 
                          tempList.forEach(function(dataItem){
                            if(dataItem.m_pid == '00000000-0000-0000-0000-000000000000'){  //it's MAIN MENU
                             //Its MainView or ParentItem View
                              <Panel key={dataItem.m_pid} title={dataItem.m_name}>
                                    {self.BindCategory(dataItem.m_name, dataItem.mid, dataItem.m_pid, dataItem.m_iscategory)}

                                    {/* check for CHILDREN           */}
                                    {self.GetChildCategory(rawList, dataItem.mid)}

                              </Panel>
                            }
                          })
                        );
                        return MainMenuArray;
                    }

                BindCategory(menuName, menuId, menumPid, isMenu){
                  debugger
                  let bindCategoryArray = [];
                  if(isMenu == true ){
                    console.log("BindCategory called "+menuName);
//THIS is CHILDVIEW that will reside inside MAINMENU
                     bindCategoryArray.push(
                      <View key={Math.random()} style={[styles.menuContainer, styles.itemContainer ]}> 
                          <Image
                             style={{width:30, height:30, padding: 2, }}
                             resizeMode="contain"
                             source={require('../../components/images/coke.jpg')} />          
                           <View style={{flexDirection:'column',flex:1, paddingHorizontal:10 }}>

                             <Text key={menuId} style={styles.textContainer}>

                              {menuName}          
                             </Text>
                             <Text numberOfLines={1} ellipsizeMode='tail' style={styles.textStyle}>
                                (Android-only) Sets the elevation of a view, using Android                  
                             </Text>
                           </View>
                       </View>);
                  }

                  return bindCategoryArray;
              }


              GetChildCategory(rawList, categoryId){
                let tempChildList = [],
                  tempCHildArray = [];

                for(let i=0; i< rawList.length; i++){
                    if(rawList[i].m_pid == categoryId){
                        tempChildList == rawList;
                    }
                }

                console.log("GetChildCategory called "+tempChildList);
                console.log(tempChildList);
                 tempCHildArray.push( tempChildList.forEach(function(dataItem){
                    if(dataItem.m_pid ==categoryId ){
                      <Panel key={dataItem.m_pid} title={dataItem.m_name}>

                            {this.BindCategory(dataItem.m_name, dataItem.mid, dataItem.m_pid, dataItem.isMenu)}

                            {/* check for CHILDREN           */}
                            {this.GetChildCategory(rawList, dataItem.mid)}

                        </Panel>            
                    }
                }));

                return tempCHildArray;
            }

            test(){
              let panelArray = [];
                panelArray.push(<Panel key={Math.random()} title="Breakfast">

                    </Panel>);
                    return panelArray;
            }

            render(){

              return(        
                <ScrollView style={styles.container}>    

                      {this.test()} //This test method shows View
                   {this.MainMethod()}  //calling above method does'nt show up View   

            </ScrollView>
                );
            }
            }    

            const mapStateToProps =state=> {
              return{
                restaurantMenuDetails: state.fetchRestaurantMenuReducer,
              }
            }

            export default connect(mapStateToProps,{
                  fetchRestaurantMenu
                })(BookmarkReservations);

1 Ответ

0 голосов
/ 10 октября 2018

После многих часов мозгового штурма я наконец нашел решение вышеупомянутого вопроса.Если кто-то застрянет с такой проблемой в своем проекте, он может искать решение ниже.Надеюсь, это кому-нибудь тоже поможет.

import React from 'react';
import {
   Image,ScrollView,StyleSheet,Text, View 

} from 'react-native';

import Panel from '../../components/BottomTabFiles/Panel';
import {fetchRestaurantMenu} from '../actions/restaurantMenuAction';
import {connect} from "react-redux";

class BookmarkReservations extends React.Component{

componentDidMount() {

  this.props.fetchRestaurantMenu("getmenu"); //calling api from redux
}

MainMenu(){
  let panelArray = [],
    self = this,
   data = this.props.restaurantMenuDetails.restaurantMenu; //getting data from api

        data.forEach(item=>{
          if(item.m_pid == '00000000-0000-0000-0000-000000000000'){ //checking for parentItem i.e. MainMenu
            console.log("test");
            panelArray.push(
              <Panel key={Math.random()} title={item.m_name}>
                {self.SubMenu(data, item.mid)}   //childView
              </Panel>
             )
          }});

        return panelArray;
}

SubMenu(data, menuId){  //data is mainList and menuId is parentId
  debugger
  let someArray = [];
  console.log("Data ");
  console.log(data+"  "+ menuId);
        data.forEach(item=>{
          if(item.m_pid == menuId && item.m_iscategory == true){ //If an item is subMenu then insert again MainMenuview 
             someArray.push( 
                <Panel key={Math.random()} title={item.m_name}>
                    {this.SubMenu(data, item.mid, item.m_iscategory)}
                </Panel>
              )
          }
          if(item.m_pid == menuId && item.m_iscategory == false){  //if its a child item of that parent item then insert it in child view

            console.log("childrenItems");
            someArray.push(  
              <View key={Math.random()} style={[styles.menuContainer, styles.itemContainer ]}>
                  <Image
                     style={{width:30, height:30, padding: 2, }}
                     resizeMode="contain"
                     source={require('../../components/images/coke.jpg')} />          
                   <View style={{flexDirection:'column',flex:1, paddingHorizontal:10 }}>

                     <Text key={Math.random()} style={styles.textContainer}>

                      {item.m_name}          
                     </Text>
                     <Text numberOfLines={1} ellipsizeMode='tail' style={styles.textStyle}>
                        {`Rs. ${item.m_isprice}`}    

                     </Text>
                   </View>
               </View>)
          }


        }); 

      return someArray;
}


  render(){          

  return(
    <ScrollView style={styles.container}>    

            {this.MainMenu()}  //calling above method

            <Panel key={Math.random()} title="BreakFast">  //this is for **Test Purpose**

               <Panel key={Math.random()} title="Tea and Bread">
                <View key={Math.random()} style={[styles.menuContainer, styles.itemContainer ]}>
                    <Image
                      style={{width:30, height:30, padding: 2, }}
                      resizeMode="contain"
                      source={require('../../components/images/coke.jpg')} />          
                    <View style={{flexDirection:'column',flex:1, paddingHorizontal:10 }}>

                      <Text key={Math.random()} style={styles.textContainer}>

                        Lemon Tea          
                      </Text>
                      <Text numberOfLines={1} ellipsizeMode='tail' style={styles.textStyle}>
                          Rs.80                  
                      </Text>
                    </View>
                </View>
               </Panel>
             </Panel>

</ScrollView>
    );
}
}


const mapStateToProps =state=> {
  return{
    restaurantMenuDetails: state.fetchRestaurantMenuReducer,
  }
}

export default connect(mapStateToProps,{
      fetchRestaurantMenu
    })(BookmarkReservations);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...