如何访问其他组件中的状态

问题描述 投票:-1回答:3

嗨,我在Home.js中处于dataSource状态,我想在UserProfil.js中对其进行访问?

Home.js

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

    this.state = {
      loading: false,
      refreshing: false,
      location: null,
      latitude:null,
      longitude:null,
      dataSource:[],
      error:null,
      appState: AppState.currentState,
    }
    //setInterval(this.displayPosition.bind(this),3000)
    this.displayPosition = this.displayPosition.bind(this);
  }

 render() {
    return (
      <SafeAreaView style={{ flex:1 }}>
        <View style={styles.main_container}>
          <FlatList style={styles.flatList}
          data={this.state.dataSource}
          extraData = {this.state}
          keyExtractor={(item, index) => item.MembreId}
          renderItem={(item) => <UserItem user={item} displayDetailForUser={this._displayDetailForUser} />}
          numColumns={numColumns}
          refreshing={this.state.refreshing}
          onRefresh={this.handleRefresh} />
        </View>
      </SafeAreaView>
    )
  }
}

如何访问dataSource数组,其中包含从UserProfil.js中的Web服务获取的一些数据,以便对其执行.map

react-native
3个回答
0
投票

UserProfil.js是与Home.js完全独立的文件吗?如果是这样,您可以为此使用redux全局状态


0
投票

如果UserProfil.js是此组件的子代,则可以使用props传递它。如果它们是独立的,则需要使用Redux或Context API。


0
投票

有3种方法可以做到这一点:

  1. 使用Redux或其他状态容器。 (推荐)
  2. 将状态保存到之前声明的全局变量中。 (不推荐)
  3. 如果HomeUserProfile耦合,则可以使用props传递数据。
© www.soinside.com 2019 - 2024. All rights reserved.