【问题标题】:Render method called twice with componentDidMount - React native使用 componentDidMount 调用两次渲染方法 - React native
【发布时间】:2020-04-17 14:04:14
【问题描述】:

我正在从 firebase 实时数据库中获取一些数据。我在构造函数中创建了一个状态并初始化为一个空数组。稍后在componentDidUpdate 方法中,我使用setState 方法更新了状态。问题是在组件中调用了两次render 方法,并且数据每次都成倍增加。

this.state = {
            values: [],
   }

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

以及渲染方法:

var val = []; //global variable declared before class declaration

render() {
    {
        this.state.values.map(item => {
            val.push(
                <List>
                    <ListItem>
                        <Text>{item["value"]}</Text>
                    </ListItem>
                </List>
                )
        })  
    }
    return(
        <View>
            {val}
        </View>
    )
}

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

【问题讨论】:

  • val 定义在哪里?
  • 它的 data.val()。我从数据库中获取价值。我将其存储在输入中。
  • 不,我的意思是来自val.push(...)val
  • 好的。我已经定义了一个全局变量。在类声明之前将其声明为数组。

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


【解决方案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>;
}

【讨论】:

  • 我试过这个。但它没有显示任何东西。我开始空白了。
  • 但是我已经在render方法中清空了数组。所以一切正常。谢谢
  • @Musthafa 全局变量从来都不是一个好主意。 I have tried this 对我来说这就像一个魅力
【解决方案2】:

我不太了解 val 变量,但这段代码应该适合你:

mapValues = list => list.map((item, index) => (
  <List key={index}>
    <ListItem>
      <Text>{item.value}</Text>
    </ListItem>
  </List>
));

render() {
  return (
    <View>
      {this.mapValues(this.state.values)}
    </View>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 2020-09-19
    • 1970-01-01
    相关资源
    最近更新 更多