【问题标题】:this.props.route.params returns value as undefinedthis.props.route.params 返回值未定义
【发布时间】:2021-04-02 21:41:52
【问题描述】:

我正在构建一个条形码阅读器应用程序,它扫描该二维码,然后获取数据并用作从 firebase 获取对象的键。为了将数据用作密钥,我需要通过另一个屏幕,但是当我检查控制台日志时,会发现扫描的密钥未定义。

本身的条码扫描器工作完美。 条码类:

export  class BarCodeScannerScreen extends Component{
   

  state = {
    CameraPermissionGranted: null,  
  }
  async componentDidMount() {
    // Ask for camera permission
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    this.setState({ CameraPermissionGranted: status === "granted" ? true : false });
  
    
  };
  

  barCodeScanned = ({ data }) => {
    //Access the Data
        
        alert(data); // shows the scanned key
        this.props.navigation.navigate('Info', {
          item: data, }); // but then it's dissapears in here.
        
  };

  render(){
      
    const { CameraPermissionGranted } = this.state;
    if(CameraPermissionGranted === null){
      // Request Permission
      return(
        <View style={styles.container}>
            <Text>Please grant Camera permission</Text>
        </View> 
      );
    }
    if(CameraPermissionGranted === false){
        // Permission denied
      return ( 
        <View style={styles.container}>
         <Text>Camera Permission Denied.</Text>
        </View> 
      );
    }
    if(CameraPermissionGranted === true){
      // Got the permission, time to scan
      return (
        <View style = {{
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
        }}>
          <BarCodeScanner
          onBarCodeScanned = {this.barCodeScanned }
          style = {{
              height:  DEVICE_HEIGHT/1.1,
              width: DEVICE_WIDTH,
          }}
          >
          </BarCodeScanner>
        </View>
      );
      
    }
  }
      
}

这是接收信息的信息屏幕:

export default class InfoScreen extends Component {
  
    constructor(props){
        super(props);
        this.state={ 
        productlist:[],
        scannedkey: this.props.route.params.item

        
        } }
        
    async componentDidMount(){
     
  
        
        firebase.database().ref(`product/${ this.state.scannedkey}`).on(
          "value",
          (snapshot) => {
            var list = [];
            snapshot.forEach((child) => {
              list.push({
                key: child.key,
                title: child.val().title,
                //details: child.val().details,
                //price: child.val().price
              });
            });
        
            this.setState({ productlist: list });
          },
          (error) => console.error(error)
        );
    }
  componentWillUnmount() {
      if (this.valuelistener_) {
        this.valueRef_.off("value", this.valuelistener_)
      }}
    
  render() {
    console.log(this.state.scannedkey); // console log shows that scanned key is undefined
 return(
     <View style={styles.container}>
       <Text>Hey</Text>
       
      <Text>{this.state.productlist.title}</Text>
     </View>
 );}}


App.js

export default function App() {
  const Drawer=createDrawerNavigator();
  return (
    <Provider store={store}>
    <NavigationContainer>
    <Drawer.Navigator initialRouteName="Barcode">
       
      <Drawer.Screen name="Barcode" component={BarCodeScannerScreen} />
      <Drawer.Screen name="Info" component={InfoScreen} />
  

    </Drawer.Navigator>
    
  </NavigationContainer>
  </Provider>

   
  );
}

我通常使用函数组件来导航,但使用类组件对我来说有点棘手。也许我错过了什么?

到目前为止,我已经尝试过:

this.props.navigation.navigate('Info', {
          item: JSON.stringify(data)  , });

但它没有用。 我会很感激你的帮助。

【问题讨论】:

  • InfoScreen 是顶级组件还是您在另一个组件中使用的组件?
  • @voxtool 如果我误解了你的问题,我深表歉意,但我在 React 方面并不完全先进 - 本机而且我也是第一次处理类组件。我的目标是扫描条形码组件中的二维码,并使用 App.js 中的数据(它是导航但没有数据)导航到 InfoScreen。我包含了 App.js 文件,也许它会让你更清楚。请告诉我是否需要重新考虑如何处理导航。
  • 你的 this.props.route.params.itemID 打错了,我想你期待的是 item,而不是 itemID
  • @lissettdm 抱歉忘记编辑了,但问题仍然存在。
  • 你正试图得到一个不存在的东西。 route.params 是指存储在 url 中的东西。通过查看传递数据的方式,您应该能够使用 InfoScreen 中的 this.props.item 访问它

标签: firebase react-native react-native-android react-native-navigation react-native-firebase


【解决方案1】:

尝试直接从 props 中使用 item,而不是从 state 中

在您的 componentDidMount 调用中,您从 state 提供已扫描密钥,从 props 提供它

 firebase.database().ref(`product/${this.props.route.params.item}`)....

您还可以在构造函数内部的状态中直接调用 this.props 而不是 props,它可以直接访问它,这就是您可以调用 的原因super(props) 而不是 super(this.props),我不确定这是否是问题所在,但在 react docs 中说不要将 props 复制到 state,因为它们会被忽略,我的朋友,这是不好的做法。

检查此链接,在大黄色注释中我指的是什么 https://reactjs.org/docs/react-component.html#constructor

【讨论】:

  • 我尝试从 props 提供它,但仍然未定义
  • 您正在从第一个屏幕正确传递数据。尝试在信息屏幕中切换到功能组件并尝试像以前一样读取参数或尝试第二种方式似乎对于类组件是正确的,如下所示:this.props.navigation.getParam(paramName, defaultValue)
猜你喜欢
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-11
  • 2022-01-14
  • 2021-07-02
相关资源
最近更新 更多