渲染方法用componentDidMount调用了两次-React Native

时间:2020-04-17 14:04:14

标签: javascript react-native firebase-realtime-database

我正在从Firebase实时数据库中获取一些数据。我已经在构造函数中创建了一个状态,并初始化为一个空数组。稍后在Wrapper<BigObject,Cmp> q; BigObject bo; bo.forCmp = 12; q.push(std::move(bo)); BigObject i = std::move(q.front()); 方法中,我用componentDidUpdate方法更新了状态。问题是setState方法在组件中被调用两次,并且每次数据都成倍增加。

render

渲染方法:

this.state = {
            values: [],
   }

componentDidMount = () => {
        firebase.database().ref('Table').once('value', (data) => {
            var input = data.val();
            this.setState({ values: input })
        })
    }

每次渲染组件时,列表项都会不断增加。我已经检查过文件,但无法找到适当的解决方案。 https://reactjs.org/docs/react-component.html#componentdidmount

2 个答案:

答案 0 :(得分:1)

val在哪里定义?

好的。我已经定义了一个全局变量。在类声明之前将其声明为数组

这就是您重复的来源。

最好这样做:

render() {
    const val = this.state.values.map((item, index) => (
        <List key={index}>
            <ListItem>
                <Text>{item.value}</Text>
            </ListItem>
        </List>
    ));

    return <View>{val}</View>;
}

答案 1 :(得分:0)

我不太了解val变量,但是这段代码应该对您有用:

namespace fs = std::filesystem;
is_root(fs::path{ "C:" }); // true
is_root(fs::path{ "D:\\"}); // true
is_root(fs::path{ "C:/users" }) // false
is_root(fs::current_path()) // usually false, unless the executable was started directly in C: or D: or any other drive