从回调函数渲染-打字稿

时间:2020-05-11 15:01:59

标签: javascript reactjs typescript react-native render

使用graphql查询时,我正在调用showUsers函数,该函数应该显示所有用户(样式已完成,以便它们可以显示为框)。但是,目前没有任何显示。

我使用的是功能组件,而不是类组件。

在我的handleSubmitForm之后调用此函数。这里我叫showUsers

  const getFriendId = React.useCallback(
    (data) => {
      if (data) {
        if (data.users.nodes.length == 0) {
          Alert.alert('User Not Found');
        } else {
          const numberOfUsers = data.users.nodes.length;
          showUsers(data, numberOfUsers);
          addFriend(Number(data.users.nodes[0].id));
        }
      }
    },
    [addFriend],
  );

showUsers():

   const showUsers = React.useCallback(
     (data: UsersLazyQueryHookResult, numberOfUsers: Number) => {
       for (var i = 0; i < numberOfUsers; i++) {
         const userId = data.users.nodes[i].id;
         const userName = (data.users.nodes[i].firstName).concat((data.users.nodes[i].lastName));
         return(
           <View style={styles.friends}>
             <View style={styles.item}>
              <Text>{userName}</Text>
             </View>
           </View>
         )
       }      
     },
     [createUserRelationMutation],
   );

这是我的表单的样子。我想我必须在这里进行编辑,但不确定如何。

return (
    <Modal
      visible={showAddFriendEmailPage}
      animationType="slide"
      transparent={true}>
      <SafeAreaView>
        <View style={styles.container}>
          <View style={styles.searchTopContainer}>
            <View>
              <Formik
                initialValues={initialValues}
                onSubmit={handleSubmitForm}
                validationSchema={validationSchema}>
                {({ handleChange, handleBlur, handleSubmit, values }) => (
                  <View style={styles.searchFieldContainer}>
                    <View style={styles.form}>
                      <FieldInput
                        handleChange={handleChange}
                        handleBlur={handleBlur}
                        value={values.email}
                        fieldType="email"
                      />
                      <ErrorMessage
                        name="email"
                        render={msg => (
                          <Text style={styles.errorText}>{msg}</Text>
                        )}
                      />
                    </View>
                    <View style={styles.buttonContainer}>
                      <Button
                        onPress={handleSubmit}>
                        <Text >Add Friend </Text>
                      </Button>
                    </View>
                  </View>
                )}
              </Formik>
            </View>
          </View>
        </View>
      </SafeAreaView>
    </Modal>
  );
};

注意:提交表格后,我只希望它们显示在按钮下方。

编辑:

我正在尝试此操作,但是有一些问题:

  1. 即使只有一个用户,我也至少会在控制台上看到LOOP输出4次。

  2. 一旦查询和变异成功运行并且还呈现/显示了用户,我将无法再次按下该按钮。这意味着我无法再提交表单并使用其他电子邮件输入重新运行查询或变异。

export const AddFriendEmailPage: React.FunctionComponent<AddFriendEmailPageProps> = ({
  toggleShowPage,
  showAddFriendEmailPage,
}) => {
  const initialValues: FormValues = {
    email: '',
  };

  const [errorMessage, setErrorMessage] = useState('');
  const [userData, setUserData] = useState<UsersLazyQueryHookResult>('');
  const [numberOfUsers, setNumberOfUsers] = useState('');
  const validationSchema = emailValidationSchema;

  useEffect(() => {
    setUserData(userData);
    setNumberOfUsers(numberOfUsers);
  }, [userData, numberOfUsers]);


  const showAlert = () => {
    Alert.alert('Friend Added');
  };

  useEffect(() => {
    if (showAddFriendEmailPage) return;
    initialValues.email = '';
  }, [showAddFriendEmailPage]);

  const _onLoadUserError = React.useCallback((error: ApolloError) => {
    setErrorMessage(error.message);
    Alert.alert('Unable to Add Friend');
  }, []);

  const [
    createUserRelationMutation,
    {
      data: addingFriendData,
      loading: addingFriendLoading,
      error: addingFriendError,
      called: isMutationCalled,
    },
  ] = useCreateUserRelationMutation({
    onCompleted: (data: CreateUserRelationMutationResult) => {
      showAlert();
    },
  });

   const showUsers = React.useCallback(
     (data: UsersLazyQueryHookResult, numberOfUsers: Number) => {
       console.log('Number of Users in Loop: ', numberOfUsers);
       for (var i = 0; i < numberOfUsers; i++) {
         const userId = data.users.nodes[i].id;
         const userName = ((data.users.nodes[i].firstName).concat(' ')).concat(data.users.nodes[i].lastName);
         console.log('Whats the Id', userId);
         console.log('UserName', userName);
         console.log('Loop');
         return(
           <View style={styles.friends}>
             <View style={styles.item}>
              <Text>{userName}</Text>
             </View>
           </View>
         )
       }      
     },
     [createUserRelationMutation],
   );

  const addFriend = React.useCallback(
    (id: Number) => {
      console.log('Whats the Id', id);
      createUserRelationMutation({
        variables: {
          input: { relatedUserId: id, type: RelationType.Friend, userId: 7 },
        },
      });
    },
    [createUserRelationMutation],
  );

  const getFriendId = React.useCallback(
    (data: UsersLazyQueryHookResult) => {
      if (data) {
        if (data.users.nodes.length == 0) {
          setErrorMessage('User Not Found');
          Alert.alert('User Not Found');
        } else {
          setUserData(data);
          //const numberOfUsers = data.users.nodes.length;
          setNumberOfUsers(data.users.nodes.length);
          showUsers(data, Number(numberOfUsers));
          addFriend(Number(data.users.nodes[0].id));
        }
      }
    },
    [addFriend],
  );

  const [loadUsers] = useUsersLazyQuery({
    onCompleted: getFriendId,
    onError: _onLoadUserError,
  });

  const handleSubmitForm = React.useCallback(
    (values: FormValues, helpers: FormikHelpers<FormValues>) => {
      console.log('Submitted');
      loadUsers({
        variables: {
          where: { email: values.email },
        },
      });
      values.email = '';
    },
    [loadUsers],
  );

  if (!addingFriendLoading && isMutationCalled) {
    if (addingFriendError) {
      setErrorMessage(addingFriendError.message);
      Alert.alert('Unable to Add Friend');
    }
  }

  return (
    <Modal
      visible={showAddFriendEmailPage}
      animationType="slide"
      transparent={true}>
      <SafeAreaView>
        <View style={styles.container}>
          <View style={styles.searchTopContainer}>
            <View style={styles.searchTopTextContainer}>
              <Text
                style={styles.searchCancelDoneText}
                onPress={toggleShowPage}>
                Cancel
              </Text>
              <Text style={styles.searchTopMiddleText}>
                Add Friend by Email
              </Text>
              <Text style={styles.searchCancelDoneText}>Done</Text>
            </View>
            <View>
              <Formik
                initialValues={initialValues}
                onSubmit={handleSubmitForm}
                validationSchema={validationSchema}>
                {({ handleChange, handleBlur, handleSubmit, values }) => (
                  <View style={styles.searchFieldContainer}>
                    <View style={styles.form}>
                      <FieldInput
                        handleChange={handleChange}
                        handleBlur={handleBlur}
                        value={values.email}
                        fieldType="email"
                      />
                      <ErrorMessage
                        name="email"
                        render={msg => (
                          <Text style={styles.errorText}>{msg}</Text>
                        )}
                      />
                    </View>
                    <View style={styles.buttonContainer}>
                      <Button
                        rounded
                        style={styles.button}
                        onPress={handleSubmit}>
                        <Text style={styles.text}>Add Friend </Text>
                      </Button>
                    </View>
                  </View>
                )}
              </Formik>
            </View>
            {showUsers(userData, Number(numberOfUsers))}
          </View>
        </View>
      </SafeAreaView>
    </Modal>
  );
};

1 个答案:

答案 0 :(得分:0)

在使用graphql查询时,我正在调用showUsers函数 应该向所有用户显示(样式已完成,以便他们可以 显示为方框)。但是,目前没有任何显示。

函数调用showUsers(data, numberOfUsers);不能仅显示项目。您必须将其渲染到某个地方。

<View style={styles.buttonContainer}>
  <Button
    rounded
    style={styles.button}
    onPress={handleSubmit}>
    <Text style={styles.text}>Add Friend </Text>
  </Button>
</View>
{showUsers(data, numberOfUsers)}

但是,这也不会立即起作用,因为在这种情况下您没有data变量。您必须使用useState。我不知道您是否可以使用React.useCallback函数以这种方式返回组件。我将showUsers(data, numberOfUsers)更改为 单独的功能组件。