【发布时间】:2022-02-17 21:28:49
【问题描述】:
我在 StackOverflow 上尝试过其他类似的问题,但没有找到解决问题的方法。
问题是我在函数内部进行 API 调用,我也在使用 async/await 进行此调用,但函数仍然返回 {"_U": 0, "_V": 0, "_W": null, "_X": null}。
通过this 和 StackOverflow 上的其他问题,我了解到这个问题的出现是因为该函数无法与 API 正常工作。
import { firebase } from '@react-native-firebase/firestore';
async function userLogin(name, password) {
await firebase.firestore().collection('users').where("name", "==", name).where("password", "==", password).get()
.then((response) => {
console.log('Response:')
if (response.docs === []) {
return
} else {
return true
}
}).catch(err => console.error(err));
}
const initialState = {
loggedIn: false,
name: '',
}
const rootReducer = (state = initialState, action) => {
if (action.type === 'LogIn') {
const data = userLogin(action.name, action.password)
if (data) {
return {
...state,
name:action.name,
loggedIn:false
}
}
else {
console.log(4);
return {
...state,
name: 'aName',
loggedIn:true
}
}
}
return state;
}
export default rootReducer;
【问题讨论】:
-
userLogin返回一个承诺。data包含一个承诺。我认为,你不能在 reducer 中使用异步函数。 -
除了@jabaa 的评论,尝试在reducer 之外调用userLogin func 并在成功响应时调度登录操作
标签: javascript reactjs react-native asynchronous async-await