[英]Render from a callback function - typescript
While using a graphql query, I am calling a showUsers
function which is supposed to show all the users (the stying is done so that they can appear as boxes).在使用 graphql 查询时,我正在调用showUsers
function ,它应该显示所有用户(已完成样式设置,以便它们可以显示为框)。 However, currently nothing shows up.但是,目前没有任何显示。
I am using a functional component, not class component.我使用的是功能组件,而不是 class 组件。
This function is called after my handleSubmitForm
.这个 function 在我的handleSubmitForm
之后被调用。 Here I call showUsers
.我在这里调用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],
);
This is how my form looks like.这就是我的表格的样子。 I guess I have to make an edit here but I am not sure how.我想我必须在这里进行编辑,但我不确定如何。
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>
);
};
Note: I only want them to show up below the button, after I submit the form.注意:我只希望它们在我提交表单后显示在按钮下方。
EDIT:编辑:
I am trying this but I have a few problems:我正在尝试这个,但我有一些问题:
Even when there's only one user, I see the LOOP
output on the console at least 4 times.即使只有一个用户,我也会在控制台上看到LOOP
output 至少 4 次。
Once the query and mutation run successfully and a user is also rendered/displayed, I can no longer press the button again.一旦查询和变异成功运行并且用户也被渲染/显示,我就不能再按下按钮了。 Which means that I can no longer submit the form and re-run queries or mutations with a different email input.这意味着我不能再提交表单并使用不同的 email 输入重新运行查询或突变。
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>
);
};
While using a graphql query, I am calling a
showUsers
function which is supposed to show all the users (the stying is done so that they can appear as boxes).在使用 graphql 查询时,我正在调用showUsers
function ,它应该显示所有用户(已完成样式设置,以便它们可以显示为框)。 However, currently nothing shows up.但是,目前没有任何显示。
A function call showUsers(data, numberOfUsers);
A function 调用showUsers(data, numberOfUsers);
can't just show items.不能只显示项目。 You have to render it somewhere.你必须在某个地方渲染它。
<View style={styles.buttonContainer}>
<Button
rounded
style={styles.button}
onPress={handleSubmit}>
<Text style={styles.text}>Add Friend </Text>
</Button>
</View>
{showUsers(data, numberOfUsers)}
But this also don't work straight away because you don't have data
variable in this context.但这也不能立即起作用,因为在这种情况下您没有data
变量。 You have to use useState
.你必须使用useState
。 I don't know if you can use React.useCallback
function to return component this way.我不知道您是否可以使用React.useCallback
function 以这种方式返回组件。 I would change showUsers(data, numberOfUsers)
to separate functional component.我会将showUsers(data, numberOfUsers)
更改为单独的功能组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.