Как передавать данные между двумя страницами? Реагировать на родную навигацию - PullRequest
0 голосов
/ 26 мая 2020

Я пытаюсь передать данные между двумя страницами реакции. У меня есть данные о newMood. js, где я могу создать новое Mood, и я хочу добавить информацию из него на страницу Home. js. Как я могу это сделать?

Вот упрощенный код из newMood. js. Есть несколько закомментированных строк моих попыток.

export default class newMood extends Component{
  static navigationOptions = {
    title: 'New Entry',
    headerStyle: {
      backgroundColor: 'white',
    },
    headerTintColor: '#00b3b3',
  };

  constructor(props){
    super(props)
    this.state={
      mood: '',
      energy: '',
      activity: '',
      sleep: '',
      journal:'',
    }
  }

  //saveData = () => {
   // const {mood, energy, activity, sleep, journal} = this.state;
   // let myArray={
   //   mood: mood,
   //   energy: energy,
   //   activity: activity,
   //   sleep: sleep,
   //   journal: journal
    //}
    //alert("mood: " + mood + "\nenergy: " + energy + "\nactivity: " + activity + "\nsleep: " + sleep + "\njournal: " + journal)
    //return (mood, energy, activity, sleep, journal);
  //};

  render() {
    const { navigate } = this.props.navigation;
    const currentMood = this.state.mood;
    const currentJournal = this.state.journal;
    return(
          <View style={styles.container}>
            <Text style={styles.mood}>Mood</Text>
            <View style={styles.container2}>
            <TouchableOpacity
              disabled={currentMood.length !== 0 && currentMood !== 'excited'}
              style={styles.button}
              onPress={() => this.setState({mood: 'excited'})}
            >
             <Text style={styles.answer}>?</Text>
            </TouchableOpacity>
            <TouchableOpacity
              disabled={currentMood.length !== 0 && currentMood !== 'happy'}
              style={styles.button}
              onPress={() => this.setState({mood: 'happy'})}
            >
             <Text style={styles.answer}>?</Text>
            </TouchableOpacity>
            </View>
            <Text style={styles.energy}>Journal</Text>
            <View style={styles.container3}>
            <TextInput
              multiline
              numberOfLines={3}
              color="white"
              style={styles.textInput}
              onChangeText={journal => this.setState({journal})}
            />
            <TouchableOpacity
              style={styles.submit}
              //onPressIn={this.saveData}
              onPressOut={() => navigate('Home')}
              //onPressOut={() => navigate('Home', { currentMood, currentEnergy, currentActivity, currentSleep, currentJournal })}
            >
             <Text style={styles.answer}>Submit</Text>
            </TouchableOpacity>
            </View>
          </View>
      );
    }
  }

Вот код из Home. js, где я пытался получить информацию, но получил сообщение об ошибке из-за неопределенного объекта:

export default class Home extends Component {
  static navigationOptions = {
    title: 'Entries',
    headerStyle: {
      backgroundColor: 'white',
    },
    headerTintColor: '#00b3b3',
  };

  render() {
    const { navigate } = this.props.navigation;
    //const { currentMood, currentJournal } = this.props.route.params
    return (
      <View style={styles.container}>
      <TouchableOpacity
        style={styles.button}
        onPress={() => navigate('newMood')}
      >
      <Text style={styles.plus}>+</Text>
      </TouchableOpacity>
      </View>
    );
  }
}

Я бы ценю любую помощь!

1 Ответ

1 голос
/ 27 мая 2020

в классе newMood отправить данные как объект с парой ключ-значение, а на другой странице получить значение по ключу

<TouchableOpacity
  style={styles.submit}
  //onPressIn={this.saveData}
  onPressOut={() => navigate('Home', { 'data': { currentMood, 
  currentEnergy, currentActivity, currentSleep, currentJournal }})}>
       <Text style={styles.answer}>Submit</Text>
   </TouchableOpacity>            

в классе Home

componentDidMount(){
  // prints the transfered data
  console.log(this.props.navigation.getParam('data'));
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...