简体   繁体   English

React Native的功能不会更新状态/不会更改UI

[英]Function for React Native doesn't update the state / doesn't change the UI

I recently started creating my first React Native app and everything has been going well until I needed to edit the state of the app to present a different page depending on what button the user pressed in the menu. 我最近开始创建我的第一个React Native应用程序,并且一切都进行得很顺利,直到需要根据用户在菜单中按下的按钮来编辑应用程序的状态以显示不同的页面。 I can call the function (toMerchLink) properly via the menu component. 我可以通过菜单组件正确调用该函数(toMerchLink)。 I even added an "alert" to test whether it would work and it did. 我什至添加了一个“警报”来测试它是否可以工作。

Below is my menu component: 以下是我的菜单组件:

import React from "react";
import { StyleSheet, Text, View, Butto } from "react-native";
import BottomNavigation, { Tab } from "react-native-material-bottom-navigation";
import Icon from 'react-native-vector-icons/MaterialIcons'

class FooterMenu extends React.Component {

  viewedTab = 0

  toMerchLink = () => {

        this.setState({
            page: 'merch'
          });



        alert('Should go to Merch now.')
        this.viewedTab = 1;
    }

  render() {
    return (
      <BottomNavigation
        activeTab={this.viewedTab}
        labelColor="white"
        rippleColor="white"
        style={{
          height: 56,
          elevation: 8,
          position: "absolute",
          left: 0,
          bottom: 0,
          right: 0
        }}
      >

        <Tab
          barBackgroundColor="#37474F"
          label="Home"
          icon={<Icon size={24} color="white" name="home"/>}

        />
        <Tab
          barBackgroundColor="#00796B"
          label="Merch"
          icon={<Icon size={24} color="white" name="shopping-cart"/>}
          onPress={() => this.toMerchLink()}
        />
        <Tab
          barBackgroundColor="#5D4037"
          label="Settings"
          icon={<Icon size={24} color="white" name="book" />}
        />

      </BottomNavigation>
    );
  }
}

export default FooterMenu;

And this here is my main App.js which stores the the logic of what to show depending on what the state is. 这是我的主要App.js,它存储根据状态显示的逻辑。 Apologies if this looks sloppy, but I am just trying to get this to work, I will improve it once I understand it more. 抱歉,如果这看起来草率,但我只是想使它生效,一旦我对它有所了解,我将对其进行改进。

import React from "react";
import { StyleSheet, Text, View } from "react-native";
import ajax from "./src/ajax";
import CoinList from "./src/components/CoinList";
import FooterMenu from './src/components/Menu';

export default class App extends React.Component {
  /*state = {
    coins: [],
    page: 'merch'
  };*/

  constructor(){
    super();
    this.state = {
      coins: [],
      page: 'home'
    }
}
  async componentDidMount() {
    const coins = await ajax.fetchInitialCoins();
    this.setState({ coins });
  }
  render() {

    if (this.state.page == "home") {
    return (
      <View style={styles.container}>
        {this.state.coins.length > 0 ? (
          <CoinList coins={this.state.coins} />

        ) : (
          <Text style={styles.header}>Simplebits</Text>
        )}
        <FooterMenu />
      </View>
    );

  }

  if (this.state.page == "merch") {
    return (
      <View style={styles.container}>
        <Text>Merch page</Text>
        <FooterMenu />
      </View>
    );

  }

  if (this.state.page == "settings") {
    return (
      <View style={styles.container}>
        <Text>Settings page</Text>
        <FooterMenu />
      </View>
    );

  }

  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center"
  },
  header: {
    fontSize: 40
  }
});

I have been trying to figure this out for quite some time, but nothing I tried seems to work. 我已经设法解决了一段时间,但是我尝试过的任何方法似乎都没有效果。 It's likely a really simple fix. 这可能是一个非常简单的修复。 Would appreciate being pointed in the right direction. 希望能指出正确的方向。 Thanks in advance! 提前致谢!

Problem is that, the tab press handler ( toMerchLink() ) is updating the state of FooterMenu component and you are conditionally rendering component in App component. 问题在于,Tab键按下处理程序( toMerchLink() )正在更新FooterMenu组件的状态,并且您有条件地在App组件中呈现该组件。 When user press tab you should updated state of App component, not the state of FooterMenu component. 当用户按下选项卡时,您应该更新App组件的状态,而不是FooterMenu组件的状态。

So the changes will be to pass a tabPressHandler to FooterMenu component, and call it when user press tab. 因此更改将是将tabPressHandler传递给FooterMenu组件,并在用户按下tab时调用它。 In the tabPressHandler change state of App component to update current page . tabPressHandler更改App组件的状态以更新当前page

Please consider following snippets 请考虑以下片段

FooterMenu 页脚菜单

class FooterMenu extends React.Component {
    constructor(props) {
      super(props);
      this.state={ currentTab: 0}
    }
    ...
    render() {
      return (
        <BottomNavigation
          activeTab={this.state.currentTab}
          labelColor="white"
          rippleColor="white"
          style={{
            height: 56,
            elevation: 8,
            position: "absolute",
            left: 0,
            bottom: 0,
            right: 0
          }}
        >
          <Tab
            ...
            onPress={() => {
                this.setState({
                    currentTab: 0
                });
                this.props.onPressHandler('home');
            }}
          />
          <Tab
            ...
            onPress={() => {
                this.setState({
                    currentTab: 1
                });
                this.props.onPressHandler('merch');
            }}
          />
          <Tab
            ...
            onPress={() => {
              this.setState({
                currentTab: 2
              });
              this.props.onPressHandler('settings');
            }}
          />
      </BottomNavigation>
   );
  }
}

App 应用程式

export default class App extends React.Component {
  ...
  tabPressHandler = (page) => {
    this.setState({
      page
    });
  }
  ...
  render() {
    ...
    if (this.state.page == "merch") {
      ...
      <FooterMenu onPressHandler={this.tabPressHandler}/>
    }
    if (this.state.page == "settings") {
      ...
      <FooterMenu onPressHandler={this.tabPressHandler}/>
    }
  }
}

Note: Try to use any Routing library, navigation would be much easier. 注意:尝试使用任何路由库,导航会容易得多。

Hope this will help! 希望这会有所帮助!

我最终根据Prasun Pal的建议研究了一个路由库,最终使用了“ React Navigation ”,仅花了几分钟时间就实现了它,现在一切正常!

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

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