Как передать данные из одного файла React. js в другой? - PullRequest
0 голосов
/ 29 марта 2020

Я бы хотел передать данные из App.js в другой .js файл в React. Я читаю и пишу из локального хранилища между файлами, но это кажется неэффективным. Я хотел бы извлечь из локального хранилища только один раз, когда компонент App.js монтируется. Это то, чем я сейчас занимаюсь.

Приложение. js:

 constructor(props) {
    super(props);
    this.state = {
      user: {},
      user_data: (localStorage.getItem('user_data')),
    }
    this.authListener = this.authListener.bind(this);
  }  
 componentDidMount() {
    this.authListener();

  }

//checks firebase for authentication
  authListener() {
    Authentication.auth().onAuthStateChanged((user) => {
      console.log(user);
      if (user) {
        this.setState({ user });
        localStorage.setItem('user', user.uid);
        this.pulldata_Health();
        this.pulldata_Meals();
        this.pulldata_Ingredients();
      } else {
        this.setState({ user: null })
        localStorage.removeItem('user');
        localStorage.removeItem('user_data')
      }
    });
  }

  //connects to database and stores data to local storage
  pulldata_Health() {
    database.collection('Health_data')
      .doc(localStorage.getItem('user'))
      .get()
      .then(doc => {
        const data = doc.data();
        localStorage.setItem('user_data', JSON.stringify(data));
        console.log(JSON.parse(localStorage.getItem('user_data')))
      }).catch(function (error) {
        console.error("Error reading health", error);
      });

Домашняя страница. js:

     constructor(props) {
            super(props);
            this.state = {
                healthData: (JSON.parse(localStorage.getItem('user_data')))
            }
        }
  componentDidMount() {
        this.GoalChecker();
        console.log(this.state.healthData);
    }

    GoalChecker() {
        if (this.state.healthData !== null) {

            if (this.state.healthData.goal === 'Gain') {
                this.setState({ gainImage: true });
                this.setState({ recompImage: false });
                this.setState({ loseImage: false });
                console.log('gainimg')
            }

            if (this.state.healthData.goal === 'Recomp') {
                this.setState({ gainImage: false });
                this.setState({ recompImage: true });
                this.setState({ loseImage: false });
                console.log('recompimg')
            }

            if (this.state.healthData.goal === 'Lose') {
                this.setState({ gainImage: false });
                this.setState({ recompImage: false });
                this.setState({ loseImage: true });
                console.log('loseimg')
            }
        }
    };

Это все работает, но извлечение из локального хранилища каждый раз, когда эта страница загружается, кажется немного неэффективным. Есть ли какой-нибудь способ отправить sh реквизиты данных пользователя с App.js на мою другую страницу?

Ответы [ 2 ]

1 голос
/ 29 марта 2020

Вы можете использовать контекст реакции. Создайте контекст в app.js / вверху вашего приложения. Оберните контейнер верхнего уровня, используя компонент контекста. Внутри любых дочерних компонентов вы можете получить доступ к реквизиту в глобальном контексте.

Отличное руководство, объясняющее, что здесь, https://kentcdodds.com/blog/how-to-use-react-context-effectively

1 голос
/ 29 марта 2020

Мне очень сложно объяснить, но я покажу вам видео с YouTube, как это сделать с помощью активных крючков. Это не очень сложный метод https://youtu.be/XuFDcZABiDQ

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...