[英]Update React Native Screen when Firebase variable changes
Hi I'm new to firebase and don't know how to make a screen in my react native app update when a certain firebase variable changes.嗨,我是 firebase 的新手,当某个 firebase 变量发生变化时,我不知道如何在我的反应原生应用程序更新中制作屏幕。
In my app's homescreen, a user's posts are fetched from firebase in componentDidMount
, and then rendered:在我的应用程序的主屏幕中,从
componentDidMount
中的 firebase 获取用户的帖子,然后呈现:
componentDidMount = () => {
this.setup();
};
setup = async () => {
const { currentUser } = await firebase.auth();
this.setState({ currentUser });
await firebase
.database()
.ref("users/" + currentUser.uid + "/posts")
.on("value", snapshot => {
this.setState({posts: snapshot.val()})
});
}
// render posts
In a separate screen, the user can choose to add a post and the firebase database is updated:在单独的屏幕中,用户可以选择添加帖子并更新 firebase 数据库:
addPost = async () => {
const { currentUser } = firebase.auth();
await firebase
.database()
.ref("users/" + currentUser.uid + "/posts")
.push({
post: // data for post
});
However, though the database is successfully changed, the homescreen doesn't update and show the newly added post till it is manually reloaded.但是,尽管数据库已成功更改,但在手动重新加载之前,主屏幕不会更新并显示新添加的帖子。 How do I add a listener to the homescreen, so that when the posts database variable changes, the screen automatically updates.
如何在主屏幕上添加一个监听器,以便当帖子数据库变量更改时,屏幕会自动更新。
If you want to share the same data between multiple screens, the best is to use Redux.如果要在多屏之间共享相同的数据,最好使用Redux。
Using Redux, all your renders function (which needs a specific data from the store) will automatically refresh if a data is updated.使用 Redux,如果数据更新,您的所有渲染 function(需要来自商店的特定数据)将自动刷新。 That way, you can only handle one firebase listener to update your redux store.
这样,您只能处理一个 firebase 侦听器来更新您的 redux 存储。
I would create a "Post" reducer and dispatch an update action every time I got something new from the firebase listener.每当我从 firebase 监听器获得新内容时,我都会创建一个“发布”减速器并调度一个更新操作。
// Actions
const ADD = 'post/ADD';
const UPDATE = 'post/UPDATE';
// Initial state
const initialState = {
posts: [],
};
// Reducer
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case ADD:
return {
...state,
posts: [...state.posts, action.post]
};
case UPDATE:
return {
...state,
posts: action.posts
};
default:
return state;
}
}
// Action Creators
export function addPost(post) {
return {
type: ADD,
post
};
}
export function updatePosts(posts) {
return {
type: UPDATE,
posts
};
}
And the listener would be like:听众会是这样的:
import { update } from 'PostRedux.js'
firebase
.database()
.ref("users/" + currentUser.uid + "/posts")
.on("value", snapshot => {
Store.dispatch(update(snapshot.val()));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.