我有一个模式,其中包含用户可以在其中更新其个人资料信息的表单。提交表单后,我想更新他们在数据库中的数据,并关闭模式。我有一个同时执行这两个操作的处理程序,我在“提交”按钮中将其称为onPress-但这在每次尝试加载屏幕时都会引发错误invariant violation- too many re-renders
。我怀疑这是因为我以错误的方式更新状态,但是我不确定为什么,因为我只调用过一次useState。我的代码如下:
const TeamEditForm = props => {
const initialState = {
newTeamName: "",
modalVisible: false,
}
const [modalVisible, setModalVisible] = useState(initialState.modalVisible)
const [newTeamName, setNewTeamName] = useState(initialState.newTeamName)
const [logo, setLogo] = useState("1")
const { teamName } = props
const { user } = useContext(UserContext)
const { uid } = user
const toggleModal = () => {
setModalVisible(!modalVisible)
}
const handleNewTeamName = text => {
setNewTeamName(text)
}
const onSubmit = (uid, newTeamName, logo) => {
updateUser(uid, newTeamName, logo)
toggleModal() /** This line is what's causing the error, if I remove it code works */
}
return (
<View>
<Modal
animationType="slide"
transparent={false}
visible={modalVisible}
supportedOrientations={["landscape"]}
>
<View style={styles.formContainer}>
<TouchableOpacity
style={{
flexDirection: "row",
justifyContent: "flex-start",
width: "100%",
}}
onPress={toggleModal}
>
<Text style={{ fontSize: 40, marginLeft: 10 }}>X</Text>
</TouchableOpacity>
<TextInput
style={[styles.teamNameInput, globalStyles.h1]}
underlineColorAndroid="transparent"
placeholder={teamName}
placeholderTextColor="#000"
onChangeText={handleNewTeamName}
/>
<LogoSelector
style={{ marginVertical: 10 }}
selected={logo}
onSelect={setLogo}
/>
<CustomButton
title="Submit"
onPress={onSubmit()}
size="sm"
/>
</View>
</Modal>
<TouchableOpacity onPress={toggleModal}>
<Text style={globalStyles.h4}> Edit Team </Text>
</TouchableOpacity>
</View>
)
}
export default TeamEditForm
答案 0 :(得分:1)
首先,您不应该像这样使用onPress。而是使用此:
<input id='stall' type="checkbox">
<button id='button'>Test
如果要使用onPress更新状态,可以这样:
onPress={() => this.firstFunction(param1) }>