访问其他组件中的状态数据

时间:2019-11-14 09:36:11

标签: react-native

嗨,我该如何访问获取其他组件中所有数据的状态?我有一个用于提取数据的Accueil组件,以及一个用于设计和显示信息的UserItem组件。所以我在Accueil组件中有一个平面列表,并且在renderItem函数的该平面列表中传递了。那么,如何在UserItem中访问状态dataSource呢?

class UserItem extends React.Component {

  render() {
    const user = this.props.user;
    const displayDetailForUser = this.props.displayDetailForUser;
    var colorConnected;

    if (user.Statut == "ON") {
      colorConnected = "#1fbc26";
    }
    else if (user.Statut == "OFF") {
      colorConnected = "#ff0303";
    }
    else {
      colorConnected = "#ffd200";
    }

    return (
      <TouchableOpacity style={styles.view_container} onPress={() =>
                        displayDetailForUser(user.MembreId, user.Pseudo, user.Photo, user.Age, user.Genre, user.Description, user.distance, user.Statut, user.localisation, user.principale )}>
        <ImageBackground source={{ uri : user.Photo}} style={{ flex: 1, aspectRatio: 1, position: 'relative', borderColor: '#d6d6d6', borderWidth: 1}}>
          <View style={[styles.bulle_presence, { backgroundColor: colorConnected } ]}></View>
          <TouchableOpacity>
            <Image style = {{aspectRatio:0.6, position:'absolute', resizeMode:'contain', height:40, width:40, right:15, top:15 }} source = {require("../Images/chat-bg.png")}/>
          </TouchableOpacity>
        </ImageBackground>
        <View style={{ backgroundColor: '#d6d6d6', padding: 6 }}>
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
            <View>
              <Text style={{ fontSize: 25 }}>{user.Age}</Text>
            </View>
            <View style={{ marginRight: 7, marginLeft: 7, backgroundColor: '#000000', width: 1, height: 26 }}></View>
            <View style={{ flexDirection: 'column', flex:1 }}>
              <Text style={{ fontSize: 13, fontWeight: '600' }}>{user.Pseudo}</Text>
              <View style={{ flexDirection: 'row', justifyContent: 'space-between'}}>
                <Text style={{ fontSize: 12 }}>{user.distance}</Text>
                <Text style={{ fontSize: 12 }}>{user.Genre}</Text>
              </View>
            </View>
          </View>
        </View>
      </TouchableOpacity>
    )
  }
}

我已经尝试过const user = this.props.dataSource,但是它不起作用。谢谢

编辑:

lass Accueil extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      refreshing: false,
      location: null,
      latitude:null,
      longitude:null,
      dataSource:[]
    }

    this.displayPosition = this.displayPosition.bind(this);
  }

  handleRefresh = () => {
    this.setState (
      {
        refreshing: true,
      },
      () => {
        setTimeout(() => {this.setState({refreshing: false,})}, 1000)
      }
    );
  };


  componentDidMount() {

    const url = "SomeUrl";
  fetch(url)
    .then(res => res.json())
    .then(res => {
      this.setState({
        dataSource: res
      });
    })
    .catch(error => {
      console.log("get data error:" + error);
    });
  }


  static navigationOptions = ({ navigation }) => {
    return {
      headerRight: () => (
        <View style={{marginLeft: 8, marginRight: 8, flexDirection: 'row', alignItems: 'center' }}>
          <TouchableOpacity style={{ marginRight: 10 }} onPress={ () =>{ }}>
              <Image style={{ width: 22, height: 22 }} source={require("../Images/search.png")} />
          </TouchableOpacity>
          <TouchableOpacity style={{marginLeft: 10, marginRight: 10 }} onPress={ () =>{{this.displayPosition()}}}>
              <Image style={{ width: 22, height: 22 }} source={require("../Images/localisation.png")} />
          </TouchableOpacity>
          <TouchableOpacity style={{marginLeft: 10 }} onPress={ () =>{ }}>
              <Image style={{ width: 22, height: 22 }} source={require("../Images/refresh.png")} />
          </TouchableOpacity>
        </View>
      ),
    };
  };
  displayPosition = () => {
    Geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          latitude: JSON.stringify(position.coords.latitude),
          longitude: JSON.stringify(position.coords.longitude),
          error: null,
        });
        console.log(this.state.latitude)

      }, 
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
    );

  }

  _displayDetailForUser = (idUser, name, photo, age, pratique, description, distance, Statut, localisation, principale ) => {
    //console.log("Display user with id " + idUser);
    this.props.navigation.navigate("UserProfil", { idUser: idUser, name:name, photo: photo, age:age, pratique:pratique, description:description,  distance:distance, Statut:Statut, localisation:localisation, principale:principale });
  }
  render() {
    return (
      <SafeAreaView style={{ flex:1 }}>
        <View style={styles.main_container}>
          <FlatList style={styles.flatList}
          data={this.state.dataSource}
          keyExtractor={(item) => item.MembreId}
          renderItem={() => <UserItem user={this.state.dataSource} displayDetailForUser={this._displayDetailForUser} />}
          numColumns={numColumns}
          refreshing={this.state.refreshing}
          onRefresh={this.handleRefresh} />
        </View>
      </SafeAreaView>
    )
  }
}

0 个答案:

没有答案
相关问题