【问题标题】:Save new data - React Native + Firebase保存新数据 - React Native + Firebase
【发布时间】:2017-10-30 07:32:26
【问题描述】:

你们中的任何人都可以给我一个用户/uid 更新的例子吗?如何提供更新?

我知道我可以这样做来提供更新:database().ref(`/users/${uid}`).update(newData),但我在哪里实现此代码?

【问题讨论】:

  • 您可以在“任何地方”执行此操作 - 取决于您的架构,哪里最有意义。如果您使用的是 redux,那么这应该是一个暴露为 updateUser 之类的操作。如果您不使用它,那么它应该是某种形式的 onChange 或您的组件具有的方法,它会调用 Firebase 调用。

标签: android reactjs firebase react-native firebase-realtime-database


【解决方案1】:

如果您使用 Redux,请在您的操作页面中使用此查询。

例如:

    In src/actions/userActions.js
    
import firebase from '../your/path/";
rootRef = firebase.database().ref();
        
export const updateUser = (newData)=> ((dispatch, getState)=> {

      // get the uid of the user here, you can get it directly from state if you stored it in state earlier, or you can use, the currentUser method from firebase if you used their auth module as well.
    
const state = getState();
let uid = state.uid;
rootRef.child(`/users/${uid}`).update(newData);
    
// dispatch something
     
);

如果你不使用 Redux, 只需将更新操作包装在组件页面中的函数中,并在需要时调用它

例如:

在 src/components/UserUpdate.js 中

// import necessary react and react native modules
import firebase from '../your/path/of/firebase config'
rootRef = firebase.database().ref();

export default class UserUpdate extends Component {
  updateUser = () => {
    // get your userId and new data ;
    rootRef.child(`users/${uid}`).update(newData);
  }

  render() {
    return ( <
      TouchableOpacity onPress = {
        this.updateUser()
      } >
      <
      Text > Update User < /Text> <
      /TouchableOpacity>
    );
  }
}

注意:

  1. newData 必须是对象(JSON 格式)

  2. 所有查询都返回 promise,因此请使用 then 和 catch 正确处理它们

  3. 我创建动作的方式可能与您的有所不同,因为我不使用 switch case,但我使用辅助函数为我生成它们。

【讨论】:

  • 我在做:savename() { this.setState({ loading: true }); update() { 数据库().ref(/users/${uid}).update(newData); }.catch((error) => { this.setState({ loading: false }); alert("ERROR!") }); } ------------------------------------ onPress={this.savename.bind()}跨度>
  • 你用 savename 做什么?只是将加载设置为true吗?这是我的理解,当你调用更新函数时,加载状态必须设置为true,然后在请求后设置为false 代码更新=()=> { this.setState({loading:true}); firebase.database().ref(/users/${uid}).update(newData).then(()=> { this.setState({loading: false}); }).catch((err)=> { this.setState ({loading: false}); // 确保加载器在发生错误时停止 console.log("Error ",err); }); } onPress = {this.update}
  • 我按照您告诉我的方式进行了操作,但是当我单击“保存”时出现错误:“找不到变量:uid”。你认为我需要导入一些东西吗?
  • 不,你没有向函数发送任何 uid,uid 只是一个变量,它不是关键字,将它作为参数传递给函数。
  • 您能举个例子说明如何解决此错误吗?我把项目放在了GitHub:github.com/JVRodrigues256/firebase_reactnative_project/blob/…
猜你喜欢
  • 2018-03-08
  • 1970-01-01
  • 2018-02-27
  • 1970-01-01
  • 2019-06-09
  • 2022-11-25
  • 2016-09-30
  • 2019-08-07
  • 1970-01-01
相关资源
最近更新 更多