我正在尝试制作自己的Blog应用,但似乎无法按预期工作。这是我的“ startSetMyBlogs”代码:
export const startSetMyBlogs = () => {
return (dispatch, getState) => {
const myBlogs = [];
const blogRef = database.ref('blogs/')
const uid = getState().auth.uid;
//join table to get blogs match with logging in user
return database.ref(`author-blog`)
.once('value', snap => snap.val())
.then(childSnapshot => {
childSnapshot.forEach((blog) => {
if (blog.val() == uid) {
blogRef.child(blog.key).once('value').then(blogSnapshot => {
myBlogs.push({
id: blogSnapshot.key,
...blogSnapshot.val()
})
})
}
})
// Dispatch another action to set redux state.
dispatch(setUserBlogs(myBlogs));
})
}
}
我的“ setUserBlogs”操作:
export const setUserBlogs = (myBlogs) => ({
type: 'SET_USER_BLOGS',
myBlogs
})
那么在将道具传递给我的BlogList组件之前,如何等待“ setUserBlogs”操作完成?
答案 0 :(得分:0)
按以下方式使用:从Firebase获得所需的操作后,立即分派操作。
return database.ref(`author-blog`)
.once('value', snap => snap.val())
.then(childSnapshot => {
childSnapshot.forEach((blog) => {
if (blog.val() == uid) {
blogRef.child(blog.key).once('value').then(blogSnapshot => {
myBlogs.push({
id: blogSnapshot.key,
...blogSnapshot.val()
})
})
}
})
dispatch(setUserBlogs(myBlogs));
})
注意:API调用是异步的,因此您必须等待数据将其分配给状态。
希望这会有所帮助。
答案 1 :(得分:0)
您需要做的就是存储并传递加载状态,直到数据准备就绪
export const startSetMyBlogs = () => {
return (dispatch, getState) => {
const myBlogs = [];
const blogRef = database.ref('blogs/')
const uid = getState().auth.uid;
//join table to get blogs match with logging in user
dispatch({type: 'SET_LOADING', payload: true});
return database.ref(`author-blog`)
.once('value', snap => snap.val())
.then(childSnapshot => {
childSnapshot.forEach((blog) => {
if (blog.val() == uid) {
blogRef.child(blog.key).once('value').then(blogSnapshot => {
myBlogs.push({
id: blogSnapshot.key,
...blogSnapshot.val()
})
})
}
})
// Dispatch another action to set redux state.
dispatch(setUserBlogs(myBlogs));
dispatch({type: 'SET_LOADING', payload: false});
})
}
}
一旦完成,就可以在组件中使用此加载状态来渲染加载器
const mapStateToProps = state => {
blogs: state.blogs,
isLoading: state.isLoading
}