繁体   English   中英

如何在 react-native 的 function 内部的组件内使用变量?

[英]How to use variable within component inside function in react-native?

我正在从实时数据库(firebase)中检索一些数据,但是,当我尝试在数据库引用调用之外检查“级别”的值时,我得到一个未定义的值,尽管它在引用中工作。

有没有办法允许访问 react-native 组件内的变量“级别”?

我在网上看到了一些使用 this.setState 来实现此目的的示例,但在 function 中似乎没有任何方法可以做到这一点。

function LevelsScreen() {
    const reference = database()
    .ref()
    .once('value')
    .then(snapshot => {
      //get Levels from db
      let levels = [];
      snapshot.forEach((child) => {
          levels.push(child.key);
      })
      console.log(levels);
  
  });
    return (
      <SafeAreaView style={styles.categories}>
        {/* Horizontal Scrollbox for Main Categories */}
        <ScrollView horizontal={true} style={styles.scrollView}>
          <View>

            {/* This function should call LevelCard to return the components with the proper titles*/}
            {levels.map(element => {
                return (<LevelCard
                level={element}/>)
                })
            }

          </View>
        </ScrollView>
      </SafeAreaView>
    );
}
  1. 您应该使用state让 react 知道要渲染什么。
  2. 从数据库中获取数据后,我们更新 state。
  3. 更新 state 会触发 React 中的重新渲染,这表示 React 在屏幕上渲染新内容。
  4. 然后,您可以向用户展示您的新 state。
function LevelsScreen() {
  // use state so that the react can know when the update the screen.
  const [levels, setLevels] = React.useState(null);

  // upon the component mount, we call the database.
  React.useEffect(() => {
    database()
      .ref()
      .once("value")
      .then((snapshot) => {
        //get Levels from db
        const levels = snapshot.map((child) => child.key);
        // update the state so react knows to re-render the component
        setLevels(levels);
      });
  }, []);

  return (
    <SafeAreaView style={styles.categories}>
      {/* Horizontal Scrollbox for Main Categories */}
      {levels ? (
        <ScrollView horizontal={true} style={styles.scrollView}>
          <View>
            {/* This function should call LevelCard to return the components with the proper titles*/}
            {levels.map((element) => {
              return <LevelCard level={element} />;
            })}
          </View>
        </ScrollView>
      ) : (
        {/* show spinner when the levels is not got from the server */}
        <ActivityIndicator />
      )}
    </SafeAreaView>
  );
}

我认为如果您可以为此使用 Promises 会更好。

function LevelsFunction() {
    return Promise(resolve=> {
    database()
    .ref()
    .once('value')
    .then(snapshot => {
    const levels = [];
    snapshot.forEach((child) => {
      levels.push(child.key);
    })
    console.log(levels);
    resolve(levels)
});

现在使用 async/await 或 then 从您想要的任何地方访问 LevelsFunction。

前任:

componentDidMount(){
    const levels = LevelsFunction().then(res => res);
    console.log(levels);
}

或者

async componentDidMount(){
    const levels = await LevelsFunction();
    console.log(levels);
}

我强烈建议您不要在 class 渲染 function 中使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM