Как передать список меню из API в Custom DrawerNavigator? - PullRequest
0 голосов
/ 14 мая 2019

Я новичок в React.Я создаю пользовательскую навигацию по ящикам с помощью DrawerNavigator.Я хотел получить список категорий из API и добавить список меню с параметром cat_id.Каждая категория будет переходить на одну и ту же страницу / экран, но параметр будет использоваться для получения списка результатов.

Я попытался создать массив для DrawerNavigator, но он не получает его, поскольку его нет в компоненте.


export default class App extends Component {
  componentDidMount() { 
    global.dState=0;
    global.dynamicData = ["Cats", "Dogs", "Lions"]
    return fetch('http://xxxx.com/Api.php?action=category')
      .then((response) => response.json())
      .then((responseJson) => { 
        this.dataSource = responseJson
      })
  }

  render() {
    return (
      <MyApp authed={this.state.ddata} />
    )
  }
}

const CustomDrawerContentComponent = (props) => (

  <Container>
    <Header style={styles.drawerHeader}>
      <Body>
        <Image
          style={styles.drawerImage}
          source={require('./assets/DrawerIcons/Logo.png')} />
      </Body>
    </Header>
    <Content>
      <DrawerItems {...props} />
    </Content>

  </Container>

);

const MyApp = DrawerNavigator({
//// Below list will come from API
  Home: {
    screen: HomeScreen,
    navigationOptions: ({ navigation }) => ({
      title: 'Home'
  })
  },
  Settings: {
    screen: SettingsScreen,
    navigationOptions: ({ navigation }) => ({
      drawerLabel: () => null
  })
  }
},
  {
    initialRouteName: 'Home',
    drawerPosition: 'left',
    contentComponent: CustomDrawerContentComponent,
    drawerOpenRoute: 'DrawerOpen',
    drawerCloseRoute: 'DrawerClose',
    drawerToggleRoute: 'DrawerToggle'
  });
  Home: {
    screen: HomeScreen,
    navigationOptions: ({ navigation }) => ({
      title: 'Home'
  })
  },
  Settings: {
    screen: SettingsScreen,
    navigationOptions: ({ navigation }) => ({
      drawerLabel: () => null
  })
  }

Ответы [ 2 ]

0 голосов
/ 15 мая 2019

Я понял это. Я переместил константу ящика в компонент, а затем сделал объект меню, используя push.

export default class App extends Component {
  componentDidMount() {
    //global.catData="testting";

    return fetch('http://******?action=category')
      .then((response) => response.json())
      .then((responseJson) => {




       this.dataSource = responseJson
       global.dState=1;
       const self=this;
          global.check="hello";
      const first = responseJson[0];


      var rdata=[];
      for (var i = 0; i < responseJson.length; i++) {
        rdata.push(responseJson[i].name);
      }
       this.setState({
        isLoading: false,
        ddata :rdata
      })
      })
  }

  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      ddata:[]

    }


  }
  render() {
    //this.findCoordinates();
  //Alert.alert(this.state.location);
  if (this.state.isLoading) {
    return (
      <View style={{flex: 1, paddingTop: 150}}>
      </View>
    );
  }

//alert(global.check);
//alert("loaded");


var temp ="";
const DD=[];
var something = this.state.ddata;
//alert(this.state.isLoading);
//alert(global.check);

//alert(global.check);
for(var d=0;d<3;d++){
  let dd=d;
  let temp = something[dd]

 DD.push({
    screen: HomeScreen,
    navigationOptions: ({ navigation }) => ({
      title: temp
  })
  });
}

 DD.unshift({
    screen: SettingsScreen,
    navigationOptions: ({ navigation }) => ({
      drawerLabel: () => null
  })
  });



const MyApp = DrawerNavigator(
   DD,
  {
    initialRouteName: "1",
    drawerPosition: 'left',
    contentComponent: CustomDrawerContentComponent,
    drawerOpenRoute: 'DrawerOpen',
    drawerCloseRoute: 'DrawerClose',
    drawerToggleRoute: 'DrawerToggle'
  });


    return (
      <MyApp />
    )
  }
}

````` 
0 голосов
/ 14 мая 2019

Не уверен, что пойму вашу проблему, но, возможно, это поможет вам: setParams

Запуск действия setParams позволяет экрану изменять параметры маршрута, что полезно для обновления.кнопки заголовка и заголовок.setParams работает как React's setState - он объединяет предоставленный объект params с текущими params.

Извлечено из документации https://reactnavigation.org/docs/en/navigation-prop.html#setparams-make-changes-to-route-params

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...