我调度数据以将其写入数据库。
const data = useCallback(() => {
const jobData = {
friend: selectedFriend,
};
dispatch(jobActions.postJob(jobData));
}, [friend]);
export const postJob = data => {
return async (dispatch, getState) => {
try {
await validateAll(data, rules, messages);
const token = await firebase
.auth()
.currentUser.getIdToken(true)
.then(function(idToken) {
return idToken;
});
const response = await fetch(
`https://XXXX.firebaseio.com/posts/${data.friend}/posts.json?auth=${token}`,
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
friend: data.friend,
})
}
);
const resData = await response.json();
dispatch({
type: "CREATED_JOB_SUCCESS",
jobCreated: true,
jobData: {
id: resData.name,
friend: data.friend,
}
});
if (!response.ok) {
throw new Error("Somthing went wrong while posting jobs");
}
} catch (errors) {
const formattedErrors = {};
errors.forEach(error => (formattedErrors[error.field] = error.message));
dispatch({
type: "CREATE_JOB_FAILED"
});
}
};
};
写成功后,我会收到警报。
useEffect(() => {
if (jobCreated) {
Alert.alert("Deine Filmempfehlung wurde versandt.", "", [
{
text: "yes",
onPress: () => {
setSelectedFriend("");
}
}
]);
}
}, [jobCreated]);
在第一次运行中,一切正常。但是,如果我在selectedFriend
中选择了另一个名称(值由React Native Picker进行选择),它仍然具有旧值。通过保存文件重新渲染Android模拟器时,该值更改为最新值。
有什么想法吗?