【发布时间】:2021-12-16 21:20:35
【问题描述】:
我正在使用 react 和 redux 来制作社交媒体应用。我将有关帖子的所有数据存储在 firebase 实时数据库中。但是当我获取它时,我无法将 firebase name 属性作为 id 分配给每个帖子。 这是负责从 firebase 获取数据的操作。
export const FetchPostStart = () => {
return {
type: actionTypes.Fetch_Post_Start
};
};
export const FetchPostSuccess = (fetchedData) => {
return {
type: actionTypes.Fetch_Post_Success,
payload: fetchedData
}
}
export const FetchPostError = (error) => {
return {
type: actionTypes.Fetch_Post_Error,
error: error
}
}
export const FetchPost = () => {
return dispatch => {
dispatch(FetchPostStart());
axios.get('/Data.json')
.then(response => {
const fetchedData = [];
for(let key in response.data){
fetchedData.push({
...response.data[key],
id: response.data.name
});
}
dispatch(FetchPostSuccess(fetchedData));
})
.catch(error => {
dispatch(FetchPostError(error));
});
}
}
这是reducer函数
case actionTypes.Fetch_Post_Start:
return {
...state,
loading:true
}
case actionTypes.Fetch_Post_Error:
return {
...state,
loading:false
}
case actionTypes.Fetch_Post_Success:
return {
...state,
loading: false,
Data: action.payload
}
id 仍未定义。
编辑 这就是我试图为新帖子存储 id 的方式。 这些是添加新帖子和删除帖子的操作函数。 firebase 名称属性在此处设置为 id。但是当我尝试删除帖子时,它会传递一个空值而不是 id。
export const NewPostSuccess = (id, postData) => {
return {
type: actionTypes.New_Post_Success,
payload: {
data: postData,
index: id
}
}
}
export const NewPostError = (error) => {
return {
type: actionTypes.New_Post_Error,
error: error
}
}
export const NewPost = (postData) => {
return (dispatch) => {
axios.post('/Data.json', postData)
.then(response => {
dispatch(NewPostSuccess(response.data.name, postData));
})
.catch(error => {
dispatch(NewPostError(error));
})
}
}
export const DeletePostSuccess = (id) => {
return {
type: actionTypes.Delete_Post_Success,
ID: id
}
}
export const DeletePost = (ID) => {
return (dispatch) => {
axios.delete('/Data/'+ ID + '.json')
.then(response => {
console.log(response.data);
dispatch(DeletePostSuccess(ID));
})
.catch(error => {
dispatch(DeletePostError(error));
})
}
}
这是减速器
case actionTypes.New_Post_Success:
const {Comment, ImageUrl, Date, User} = action.payload.data;
const id = action.payload.index;
console.log(id+"Reducer function")
return {
...state,
loading: false,
Data: [
...state.Data,
{Comment, ImageUrl, Date, User},
id
],
}
case actionTypes.Delete_Post_Success:
return {
...state,
loading: false,
}
【问题讨论】:
标签: reactjs firebase firebase-realtime-database react-redux