问题描述
我正在使用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()} />
);
}
// ...