【问题标题】:how to render a react navigate instead of a component?如何呈现反应导航而不是组件?
【发布时间】:2020-04-07 08:53:58
【问题描述】:

我正在制作一个从 API 获取数据的验证表单。所以,我有一个名为“isLogged”的状态。

我将它初始化为 false,然后如果身份验证有效,它会更改为 true。

所以,我正在尝试使用 if 条件为 "isLogged" === true 呈现 if-else 语句,然后我应该将用户导航到仪表板页面

否则当“isLogged”为假时,我会渲染整个表单组件,

但我不知道如何在没有 onPress 或渲染组件的情况下在屏幕之间导航用户,我只是想调用一个函数来导航或其他东西

代码:

class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      username: null,
      password: null,
      isLogged: false,
    }
  }

  render() {
    if (this.state.isLogged) {
        # the command which navigate the user to Dashboard page
    } else {
      return (
        # The whole component code>
      );
    }
  }
}

【问题讨论】:

  • 你在哪里使用 setState 使 isLogged 为真?

标签: reactjs react-native react-native-navigation


【解决方案1】:

你可以用这个:

render() {
    if (this.state.isLogged) {
        this.props.navigation.navigate("Dashboard");
    }


 return (
        # The whole component code>
      );

  }

【讨论】:

  • 谢谢你,感谢你的帮助:D
【解决方案2】:

检查这些类型的更好的方法是使用 react 提供的 Lifecycle 钩子,因为您尽可能使用干净的渲染方法。 它是 componentDidMount。

    class Login extends Component {
      constructor(props) {
        super(props);

        this.state = {
          username: null,
          password: null,
          isLogged: false,
        }
      }
     componentDidMount(){
       if (this.state.isLogged) {
            this.props.navigation.navigate("Dashboard");
        }
     }
      render() {
        return (
            # The whole component code>
         );
      }
    }

如果您发现错误,可以找到未定义的导航,您需要通过更高的组件“WithNavigation”传递它。它会将导航对象添加到您的道具中。 以下是使用WithNavigation的代码。

    import { withNavigation } from 'react-navigation';
     class Login extends Component {
      constructor(props) {
        super(props);

        this.state = {
          username: null,
          password: null,
          isLogged: false,
        }
      }
     componentDidMount(){
       if (this.state.isLogged) {
            this.props.navigation.navigate("Dashboard");
        }
     }
      render() {
        return (
            # The whole component code>
         );
      }
    }
export default withNavigation(Login);

有关生命周期挂钩的更多信息,请阅读article

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 2017-05-12
    • 2020-10-23
    • 2019-09-24
    • 2017-08-24
    • 2018-07-28
    • 1970-01-01
    相关资源
    最近更新 更多