[英]CheckBoxes React Native Map function returns error: Too many re-renders. React limits the number of renders to prevent an infinite loop
I have this code, that should draw checkbox'es.我有这个代码,应该绘制复选框。
here is my Hashtags.js file:这是我的 Hashtags.js 文件:
import React, { useState } from 'react';
import {StyleSheet, View, Image} from 'react-native';
import { CheckBox } from 'react-native-elements';
const HashtagsList =[
{checked: false, title: '#tip1'},
{checked: false, title: '#tip2'},
{checked: false, title: '#tip3'},
{checked: false, title: '#tip4'},
{checked: false, title: '#tip5'},
{checked: false, title: '#tip6'},
];
const Hashtags = props => {
const [hashtags, setHastags] = useState([]);
setHastags(HashtagsList);
const toggleCheckbox = (title) =>{
const checkedHashtags = hashtags.find((hashtag) => hashtag.title === title);
checkedHashtags.checked = !checkedHashtags.checked;
const checkboxes = Object.assign({}, hashtags, checkedHashtags);
setHastags({ checkboxes });
};
hashtags.map((hashtag, i) => {
console.log(hashtag);
return (
<CheckBox
key = {i}
title = {hashtag.title}
checkedIcon={<Image style={styles.chekBoxPic} source={require('../assets/svg/checked.svg')} />}
uncheckedIcon={<Image style={styles.chekBoxPic} source={require('../assets/svg/unchecked.svg')} />}
checked={hashtag.checked}
onPress={() => toggleCheckbox(hashtag.title)}
/>
);
})
};
const styles = StyleSheet.create({
chekBoxPic:{
width: 22,
height: 22,
},
});
export default Hashtags;
My main.js page looks like this:我的 main.js 页面如下所示:
...
<View type={styles.someStyle}>
<Hashtags />
</View>
...
But i get error:'Too many re-renders.但我得到错误:'太多的重新渲染。 React limits the number of renders to prevent an infinite loop.'
React 限制渲染次数以防止无限循环。 Where I make a mistake?
我哪里出错了?
I thinks its probably because of setHastags(HashtagsList)
which cause Hashtags component to end up in an infinite loop.我认为这可能是因为
setHastags(HashtagsList)
导致 Hashtags 组件以无限循环结束。
you can initialize the initial HashtagsList like:您可以像这样初始化初始 HashtagsList:
const [hashtags, setHastags] = useState(HashtagsList);
I think the problem is in the first few lines of your HashTags
component:我认为问题出在
HashTags
组件的前几行:
const Hashtags = props => {
const [hashtags, setHastags] = useState([]);
// Every time your react component re-renders, it sets the state
// Of the hashtags. This causes the component to end up in an infinite loop
setHastags(HashtagsList);
}
Instead of setting the initial hashtags separately, you can initialize it in the useState
call, like this:您可以在
useState
调用中初始化它,而不是单独设置初始主题标签,如下所示:
const Hashtags = props => {
const [hashtags, setHastags] = useState(HashtagsList);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.