简体   繁体   中英

How to get data from a screen in React-Native?

I have a Subscription screen that has a useEffect hook that updates a isSubbscribed useState.

I am implementing this screen in the ApprRoot as a subscription paywall. I simply need to get this useState variable isSubscribed and use it in the appRoot to see the data. How can I get this data from the Subscription screen?

for Example in my AppRoot.jsx:

const subbed =  *subScreen use State Variable* 
return (

{ subbed ? (
                        <Stack.Navigator>  
                            <Stack.Group>
                                <Stack.Screen
                                    name="SubScreen"
                                    component={SubScreen}
                                    initialParams={{ initialroute: 'Home' }}
                                />
                                </Stack.Group>
                            </Stack.Navigator>  
                        ) : (
                        <NavigationRoot /> 
                        )}
)

Subscreen.jsx has a variable such as this

  const [subbed, setSubbed] = useState([]);

How am I able to use this useState in the approot file? I cannot just simply export it?

I'm expecting to be able to get the useState variable subbed and use it to generate the proper screens.

Below is the full subScreen where the ownedSubscriptions and Setowned are being passed from the appRoot. I need the subScreen to be shown on launch if not subscribed, but be able to be accessed on launch as well to not show if ownedSubscriptions is true is not empty.

const SubScreen = ({ownedSubscriptions,setOwnedSubscriptions}) => {

  const {
    connected,
    subscriptions,
    getSubscriptions,
    currentPurchase,
    finishTransaction,
  } = useIAP();


  console.log('connected: ',connected);

  //[ownedSubscriptions, setOwnedSubscriptions] = set useState(

  const handleGetSubscriptions = () => {
        getSubscriptions({skus: ['sku']}).then( ()=>{
          console.log('Got Subscriptions')
        }).catch( () => {
          console.log('failed to get subscriptions')
        })
      }


  const handleBuySubscription = async (
      productId,
      offerToken,
    ) => {
      if (isPlay && !offerToken) {
        console.warn(
          `There are no subscription Offers for selected product (Only requiered for Google Play purchases): ${productId}`,
        );
      }
      try {
        await requestSubscription({
          sku: productId,
          ...(offerToken && {
            subscriptionOffers: [{sku: productId, offerToken}],
          }),
        });
      } catch (error) {
        if (error instanceof PurchaseError) {
          errorLog({message: `[${error.code}]: ${error.message}`, error});
        } else {
          errorLog({message: 'handleBuySubscription', error});
        }
      }
    };
  
    useEffect(() => {      
      const checkCurrentPurchase = async () => {
        try {
          if (currentPurchase?.productId) {
            await finishTransaction({
              purchase: currentPurchase,
              isConsumable: true,
            });
  
            setOwnedSubscriptions((prev) => [
              ...prev,
              currentPurchase?.productId,
            ]);
          }
        } catch (error) {
          if (error instanceof PurchaseError) {
            errorLog({message: `[${error.code}]: ${error.message}`, error});
          } else {
            errorLog({message: 'handleBuyProduct', error});
          }
        }
      };
  
      checkCurrentPurchase();
    }, [currentPurchase, finishTransaction]);


    console.log(ownedSubscriptions + ' owned') //returns lxm_1999_1m_1w0

    return (
      <ScrollView contentContainerStyle={contentContainerStyle}>
        <State connected={connected} storekit2={isIosStorekit2()} />
  
        <Box>
          <View style={styles.container}>
            <Heading copy="Subscriptions" />
  
            {subscriptions.map((subscription, index) => {
              const owned = ownedSubscriptions.find((pId) => {
                return isAmazon
                  ? pId === constants.amazonBaseSku
                  : pId === subscription.productId;
              });
              return (
                <Row
                  key={subscription.productId}
                  fields={[
                    {
                      label: 'Subscription Id',
                      value: subscription.productId,
                    },
                    {
                      label: 'type',
                      value:
                        'type' in subscription
                          ? subscription.type
                          : subscription.productType,
                    },
                  ]}
                  isLast={subscriptions.length - 1 === index}
                >
                  {owned && <Text>Subscribed</Text>}
                  {!owned &&
                    isPlay &&
                    // On Google Play Billing V5 you might have  multiple offers for a single sku
                    'subscriptionOfferDetails' in subscription &&
                    subscription?.subscriptionOfferDetails?.map((offer) => (
                      <Button
                        title={`Subscribe ${offer.pricingPhases.pricingPhaseList
                          .map((ppl) => ppl.billingPeriod)
                          .join(',')}`}
                        onPress={() => {
                          handleBuySubscription(
                            subscription.productId,
                            offer.offerToken,
                          );
                        }}
                      />
                    ))}
                  {!owned && (isIos || isAmazon) && (
                    <Button
                      title="Subscribe"
                      onPress={() => {
                        handleBuySubscription(subscription.productId);
                      }}
                    />
                  )}
                </Row>
              );
            })}
          </View>
  
          <Button
            title="Get the subscriptions"
            onPress={handleGetSubscriptions}
          />
        </Box>
      </ScrollView>
    );
};

const styles = StyleSheet.create({
  container: {
    marginBottom: 20,
  },
});

export default SubScreen;

the simplest way I believe would be to define your state variable in your parent component (so apRoot) and to pass it down to your screen as props, along with it setSubbed (so 2 props).

So your AppRoot.jsx would be like:

const [subbed, setSubbed] = useState([]);
return (

{ subbed ? (
                        <Stack.Navigator>  
                            <Stack.Group>
                                <Stack.Screen
                                    name="SubScreen"
                                    initialParams={{ initialroute: 'Home' }}>
                                    {props => <SubScreen {...props} subbed={subbed} setSubbed={setSubbed} />}
                                </Stack.Screen>
                                </Stack.Group>
                            </Stack.Navigator>  
                        ) : (
                        <NavigationRoot /> 
                        )}
)

Now you can update it from your child component (using setSubbed) and use it from your parent component.

You child component would be something like this:

function SubScreen({subbed, setSubbed}) {}
// or
const SubScreen = ({subbed, setSubbed}) => {}

If you need it from several other components, or even nested components, you might want to look into contexts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM