[英]Render method called twice with componentDidMount - React native
I'm fetching some data from the firebase realtime database.我正在从 firebase 实时数据库中获取一些数据。 I have created a state in the constructor and initialised as an empty array.我在构造函数中创建了一个 state 并初始化为一个空数组。 Later in the componentDidUpdate
method, I have updated the state with setState
method.稍后在componentDidUpdate
方法中,我使用setState
方法更新了 state。 The issue is the render
method called twice in the component and data is getting multiplied each time.问题是在组件中调用了两次render
方法,并且数据每次都成倍增加。
this.state = {
values: [],
}
componentDidMount = () => {
firebase.database().ref('Table').once('value', (data) => {
var input = data.val();
this.setState({ values: input })
})
}
And the render method:和渲染方法:
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>
)
}
And the list item is keep getting multiplied each time when the component renders.每次组件呈现时,列表项都会不断增加。 I have checked the doc but couldn't get a proper solution.我已经检查了文档,但找不到合适的解决方案。 https://reactjs.org/docs/react-component.html#componentdidmount https://reactjs.org/docs/react-component.html#componentdidmount
Where is
val
defined?val
在哪里定义?Okay.好的。 That I have defined a global var.我已经定义了一个全局变量。 Declared it as an array before the class declaration在 class 声明之前将其声明为数组
That's where your duplication comes from.这就是你的重复来自哪里。
Better do it this way:最好这样做:
render() {
const val = this.state.values.map((item, index) => (
<List key={index}>
<ListItem>
<Text>{item.value}</Text>
</ListItem>
</List>
));
return <View>{val}</View>;
}
I didn't understand well the val variable but this code should work for you:我不太了解 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>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.