【问题标题】:Wrong button displayed for 'undefined' in React-Native在 React-Native 中为“未定义”显示错误的按钮
【发布时间】:2020-08-18 09:56:56
【问题描述】:

我正在使用 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

我的代码是这样写的显示...为什么?由于应用程序的初始启动/运行没有将任何变量传递给“道具”,我不明白为什么没有显示正确的按钮。感谢任何帮助。

【问题讨论】:

    标签: react-native react-native-router-flux


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您提供的信息,看来这实际上是问题所在……非常感谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 2019-02-27
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    相关资源
    最近更新 更多