Home > Back-end >  how to console different js file variable
how to console different js file variable

Time:11-01

In short just imagen, i have two screen such as screen1.js & screen2.js

screen1.js

import React, { useState, useEffect } from 'react';
import { StyleSheet, View, ScrollView, Dimensions, RefreshControl, Text, SafeAreaView, Fragment } from 'react-native';


const TTrail = () =>{

const information = [1001,1002,1003,1004,1005];
  
}

export default TTrail;

so as you can see i have an array in screen1.js which is information.Now i want to console this information in another file which is screen2.js

screen2.js

import React, { useState, useEffect } from 'react';
import { StyleSheet, View, ScrollView, Dimensions, RefreshControl, Text, SafeAreaView, Fragment } from 'react-native';
import TTrail from './screen1';


const Trail = () =>{

console.log(information);
  
}

export default Trail;

So, How can work this things successfully! i want to console.log(information) in screen2.js.

anyone can help me to work it. ThankYOU in advance for trying!!!

CodePudding user response:

So you are trying to share a state between components, you can accomplish this by several ways:

Lift up state

This case you can make an information state in the parent component and share it with other components as prop and change the state by a callback function like informationHandleCallback()

export default function App() {
  const [information, setInformation] = useState([]);
  const informationHandleCallback = (data) => {
    setInformation(data);
  };
  return (<>
    <TTrail informationHandleCallback = { informationHandleCallback } /> //pass callback func to the desire component as prop
    <Trail information = { information } /> //share information state
  </>
  );
}

const TTrail = ({ informationHandleCallback }) => {

  /**
  You can change the desire state by an event 
  or something like that.
  
  Here the callback function will be called 
  during first render of the component
  **/
  useEffect(() => {
    const information = [1001, 1002, 1003, 1004, 1005];
    informationHandleCallback(information);
  }, []);

  return <> screen 1 </>;
};

const Trail = ({ information }) => {
  console.log(information);
  return <> screen 2 </>;
};

Context

You can use React useContext() hook to share state between components. In this case you don't necessarily need to put the state in parent component and use callback function.

Other state management libraries:

You can use other libraries depending on your use case like Redux, MobX and so on.

Cheers!

CodePudding user response:

U can pass the between from one screen to another screen by parama. screen 01: navigation.navigate('SecondPage', { paramKey: userName, }) Screen 02

route.params.paramKey

  • Related