地图功能在表示组件中不起作用的任何原因吗?

时间:2017-06-09 00:58:40

标签: javascript reactjs react-native

有人可以帮我弄清楚为什么我的组件中的地图功能没有运行?我从firebase获取一些数据并迭代它,将每个项目(歌曲)推送到我的容器组件状态(数组)。然后我将该数组传递给我的表示组件。我在演示组件中安装了console.log,以确保它可以从屏幕截图中看到它。但无论出于何种原因,地图没有在阵列上运行,因此屏幕上没有显示任何内容。我确定它是一个数组,我确信它有可用的map方法。字面上不知道为什么它不会在这一点上运行。任何帮助将不胜感激。

enter image description here

enter image description here

以下是演示组件的完整代码

import React from 'react';
import { View, Text, ScrollView, StyleSheet } from 'react-native';
import { List, ListItem } from 'native-base';
import PropTypes from 'prop-types';

function SongList (props) {
  return (
    <View style={styles.container}>
      {console.log(props.availableSongs)}
      {props.availableSongs.map((song) => {
        console.log(song)
        return <Text>{song.songName}</Text>
      })}
    </View>
  );
}

SongListPropTypes = {
  availableSongs: PropTypes.array.isRequired
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 140
  }
})

export default SongList;

及其父组件

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { db } from '~/config/firebase';
import SongList from './SongList';

class SongListContainer extends Component {
  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    uid: PropTypes.string.isRequired
  }
  constructor (props) {
    super(props);

    this.state = {
      availableSongs: []
    }
  }
  componentDidMount () {
    const ref = db.ref(`users/${this.props.uid}/availableTracks/`);

    ref.once('value', (snapshot) => {
      snapshot.forEach((childSnapshot) => {
        const childKey = childSnapshot.key;
        const song = childSnapshot.val();

        this.setState(() => {
          availableSongs: this.state.availableSongs.push(song)
        })
      });
    });
  }
  render () {
    return (
      <SongList availableSongs={this.state.availableSongs}/>
    );
  }
}

function mapStateToProps ({authentication}) {
  return {
    uid: authentication.uid
  }
}

export default connect(mapStateToProps)(SongListContainer);

1 个答案:

答案 0 :(得分:0)

这里的问题是,一旦调用setState,状态就不会立即更新,但是在将值设置为state之前将调用render方法。

这种情况特别是因为有来自firebase的提取调用。

此处的一个简单解决方法是向您的setState()

添加回调
 yourFunction(){
  this.setState(() => {
      availableSongs: this.state.availableSongs.push(song)
    }, this.updateStateFunction); 
   }  
 updateStateFunction(){
   this.props.updateStateFunction(this.state)
 }

这样的事情应该有效。