【问题标题】:Calling two functions in OnPress throws "too many rerenders" error在 OnPress 中调用两个函数会引发“重新渲染过多”错误
【发布时间】:2020-02-11 17:14:49
【问题描述】:

我有一个模式,其中包含用户可以更新其个人资料信息的表单。提交表单后,我想更新他们在数据库中的数据,并关闭模式。我有一个处理程序可以同时执行这两种操作,我在提交按钮中调用 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

【问题讨论】:

    标签: react-native react-hooks


    【解决方案1】:

    首先你不应该像这样使用 onPress。而是使用这个:

    onPress={() =&gt; this.firstFunction(param1) }&gt;

    如果你想用 onPress 更新状态,你可以这样做:

    onPress={() =&gt; this.setState({ submit: !this.state.submit })}

    【讨论】:

    • 我不确定这如何解决我的问题,而且我没有使用 setState 我正在使用反应挂钩。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 2021-02-03
    • 2019-10-17
    • 2021-06-20
    • 1970-01-01
    • 2018-11-06
    相关资源
    最近更新 更多