首页 > 解决方案 > 使用上下文返回未定义 - 反应原生

问题描述

我想要一个页面,其中包含从后端获取的数据列表。列表中的每个值都有一个“获取更多详细信息”按钮,单击该按钮应显示每个项目的单个数据。我正在尝试使用 useContext 挂钩将项目数据传递到下一页,但数据在下一页中显示为未定义。

GetOrders.js

export const orderContext = React.createContext()
const GetOrders = ({ navigation }) => {

renderOrdersData = ({ item }) => {
    return (
      <orderContext.Provider value={ item }>

      <TouchableOpacity onPress={() => showAddress(item)} style={[styles.item]}>
        <View style={styles.textstyles}>
       
          <View style={styles.contentstyle}>
            <Text style={styles.title}>Name: {item.customer.name}</Text>
            <Text style={styles.title}>Quantity: {item.orders.quantity} </Text>
            <Text style={styles.title}>Contact: {item.customer.contact}</Text>
          </View>
        
          <View style={styles.paidbuttonstyles} >
            <Button title="Get more details"
              onPress={() => navigation.navigate('CustomerOrder') }
            />
          </View>
        </View>
      </TouchableOpacity>
      </orderContext.Provider>


    );
  };

return (
        <SafeAreaView style={styles.container}>
          <Text style={styles.textcss}> Your Pending orders are </Text>
          <FlatList
            style={styles.listcolor}
            data={orders}
            renderItem={renderOrdersData}
          />
        </SafeAreaView>
      );
}

客户订单.js

import { orderContext } from './GetOrders'
const CustomerOrder = ({ navigation }) => {

  let items = useContext(orderContext)


  showAddress = () => {

    console.log(" inside showadress" + items);

    console.log(" inside showadress json " + JSON.stringify(items));
   }

   return (
     <View style={styles.dismissbuttonstyles} >
        <Button title="Get Customer address"
          onPress={() => showAddress()}
        />
      </View>
   );
}

每当我按下“GetCustomer address”按钮时,都会出现异常

[Tue Sep 01 2020 19:20:50.443]  LOG       inside showadressundefined
[Tue Sep 01 2020 19:20:50.459]  LOG       inside showadress json undefined
[Tue Sep 01 2020 19:20:50.461]  ERROR    TypeError: undefined is not an object

任何帮助,将不胜感激?谢谢

标签: javascriptreactjsreact-hooksreact-context

解决方案


推荐阅读