Реактивно ждите, прежде чем делать какую-то задачу - PullRequest
0 голосов
/ 31 марта 2019

Эй, я пытаюсь визуализировать некоторые карты, такие как тиндер, чтобы он работал, но только когда я использую данные, которые уже есть в проекте, когда я пытаюсь использовать данные, полученные из базы данных, они не отображаются, потому что они рендерит карты до получения данных из Firebase, так как я могу это сделать?

Я пытался использовать this.setstate, но без изменений

я получаю такие данные и устанавливаю их в массиве

componentWillMount() {


    Users = [
    ]

    var query = firebase.database().ref("users").orderByKey();
    query.once("value")
      .then(function(snapshot) {
        snapshot.forEach(function(childSnapshot) {
          // key will be "ada" the first time and "alan" the second time
          var key = childSnapshot.key;
          // childData will be the actual contents of the child
          var childData = childSnapshot.val();
          Users.push({ id: key, uri: {uri: childData.photo} })
      });
    });
}



renderUsers = () => {

    console.log(Users)
    return Users.map((item, i) => {


      if (i < this.state.currentIndex) {
        return null
      }
      else if (i == this.state.currentIndex) {

        return (
          <Animated.View
            {...this.PanResponder.panHandlers}
            key={item.id} style={[this.rotateAndTranslate, { height: SCREEN_HEIGHT - 120, width: SCREEN_WIDTH, padding: 10, position: 'absolute' }]}>
            <Animated.View style={{ opacity: this.likeOpacity, transform: [{ rotate: '-30deg' }], position: 'absolute', top: 50, left: 40, zIndex: 1000 }}>
              <Text style={{ borderWidth: 1, borderColor: 'green', color: 'green', fontSize: 32, fontWeight: '800', padding: 10 }}>LIKE</Text>

            </Animated.View>

            <Animated.View style={{ opacity: this.dislikeOpacity, transform: [{ rotate: '30deg' }], position: 'absolute', top: 50, right: 40, zIndex: 1000 }}>
              <Text style={{ borderWidth: 1, borderColor: 'red', color: 'red', fontSize: 32, fontWeight: '800', padding: 10 }}>NOPE</Text>

            </Animated.View>

            <Image
              style={{ flex: 1, height: null, width: null, resizeMode: 'cover', borderRadius: 20 }}
              source={item.uri} />
            <Text>{item.id}</Text>
          </Animated.View>
        )
      }
      else {
        return (
          <Animated.View

            key={item.id} style={[{
              opacity: this.nextCardOpacity,
              transform: [{ scale: this.nextCardScale }],
              height: SCREEN_HEIGHT - 120, width: SCREEN_WIDTH, padding: 10, position: 'absolute'
            }]}>
            <Animated.View style={{ opacity: 0, transform: [{ rotate: '-30deg' }], position: 'absolute', top: 50, left: 40, zIndex: 1000 }}>
              <Text style={{ borderWidth: 1, borderColor: 'green', color: 'green', fontSize: 32, fontWeight: '800', padding: 10 }}>LIKE</Text>

            </Animated.View>

            <Animated.View style={{ opacity: 0, transform: [{ rotate: '30deg' }], position: 'absolute', top: 50, right: 40, zIndex: 1000 }}>
              <Text style={{ borderWidth: 1, borderColor: 'red', color: 'red', fontSize: 32, fontWeight: '800', padding: 10 }}>NOPE</Text>

            </Animated.View>

            <Image
              style={{ flex: 1, height: null, width: null, resizeMode: 'cover', borderRadius: 20 }}
              source={item.uri} />
            <Text>{item.id}</Text>
          </Animated.View>
        )
      }
    }).reverse()
  }

эта функция рендеринга карт

1 Ответ

1 голос
/ 01 апреля 2019

Любая асинхронная операция занимает некоторое время, пока не решится ... если вы хотите использовать setState для решения вашей проблемы ... вот как:

  state = {
    users: null,
  };

  componentDidMount() {
    users = [];

    const query = firebase
      .database()
      .ref('users')
      .orderByKey();
    query.once('value').then((snapshot) => {
      // Here you users are available:

      this.setState({ users });
    });
  }

  render() {
    const { users } = this.state;
    if (!users) return null;

    return users.map(...);
  }

componentWillMount больше не должен использоваться

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