在React-Native中为``未定义''显示了错误的按钮

问题描述

我正在使用React Native,并且在“初始”屏幕(称为“主页”)中难以识别“未定义”。这是代码。

Routes.js

import React from 'react'
import { Router,Scene } from 'react-native-router-flux'
import Home from './Home.js'
import About from './About.js'
import Login from './Login.js'
import Other from './Other.js'

const Routes = () => (
   <Router>
      <Scene key = "root">
         <Scene key = "home" component = {Home} title = "Home" initial = {true} />
         <Scene key = "about" component = {About} title = "About" />
         <Scene key = "login" component = {Login} title = "Login" />
         <Scene key = "other" component = {Other} title = "Other" />
      </Scene>
   </Router>
)
export default Routes

Home.js

import React,{ useState,useContext,createContext } from 'react'
import { Button,TouchableOpacity,Text } from 'react-native';
import { Actions } from 'react-native-router-flux';

import { LogContextProvider,LogContext } from './LogContext'

const Home = (props) => {
const status = useContext(LogContext);

   const goToAbout = () => {
      Actions.about()
   }
   const goToLogin = () => {
      Actions.login()
   }

      console.log('props called: ' + props.address);  //displays undefined
      console.log('props called: ' + props.name);  //displays undefined
      console.log('props called: ' + props.login);  //displays undefined


   return (
         <LogContext.Provider value={status}>
      <TouchableOpacity style = {{ margin: 128 }} onPress = {goToAbout}>
         <Text>This is HOME!</Text>
      </TouchableOpacity>
      {props.login === "undefined" ? (
        <Button
          title="Go to Login"
          onPress={goToLogin}
        />
      ) : (
        <Button
          title="Do Something"
          onPress={() => Actions.Other()}
        />
      )}
         </LogContext.Provider>
   )
}
export default Home

编写我的代码,以便在应用程序启动时,“ props.login”为“未定义”(由“ console.log”确认),但是没有正确的按钮(“转到登录”)显示...为什么?由于该应用的初始启动/运行未将任何变量传递给'props',所以我不明白为什么未显示正确的按钮。感谢您的帮助。

解决方法

通过查看您的代码,我认为问题在于您检查的是字符串"undefined"而不是undefined。这些不相等,因此将不会显示“转到登录”按钮。因此更改:

// ...
{
  props.login === undefined ? (
    <Button title="Go to Login" onPress={goToLogin} />
  ) : (
    <Button title="Do Something" onPress={() => Actions.Other()} />
  );
}
// ...

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...