【问题标题】:firebase :: Cannot read property 'props' of nullfirebase :: 无法读取 null 的属性“道具”
【发布时间】:2017-01-14 22:08:57
【问题描述】:

您好,我正在尝试将 react-router 与 firebase 一起使用。但它给了我这个错误。

无法读取 null 的属性“props”

这正是代码,我正在使用我的 react-router

Down 代码作为 loginpanel 组件在组件上。

else if (this.email.value === currentObject.username && this.password.value === currentObject.password && user_id)
 {
     var data25 = '';
     var groupid = '';

     var query = firebase.database().ref("/Users_group").orderByChild('id').equalTo(user_id);
     query.on("child_added", function hello (snapshot) {

         data25 = snapshot.val();

         groupid = data25.User_Group_id;

         AppActions.createComment(currentObject.username, currentObject.password, user_id, groupid);

//error is here,

         this.props.router.push('Index');
     },()=>{

     });

 }

我的反应路由器在 main.jsx 上声明 我的 react-router 看起来像这样。

       <Router history={hashHistory}>
      <Route path="/" component={Loginpanel}/>
      <Route path="Index" component={Index}/>
      <Route path="Form" component={Form} />
      <Route path="Checkindex" component={Index}/>
      <Route path="Signup" component={Signup}/>
      <Route path="Admin" component={Admin}/>
      <Route path="AdminEditDetails" component={AdminEditDetails}/>
      <Route path="AdminDetails" component={AdminDetails}/>

     </Router>,

【问题讨论】:

  • 该代码来自哪个组件,哪个函数,该函数在哪里调用,第一个sn-p代码的相关性是什么?请发布更完整的代码示例,您也错误地使用了推送
  • 它的代码来自 Loginpanel 组件。
  • 我的浏览器将错误指向 this.props.router.push('Index'); ....你能指导我为什么错误地使用 push 并且我的代码在 loginpanel 页面上,并且如果我试图将另一个组件名称作为 Index
  • @DominicTobias 你能帮我解决这个问题吗

标签: reactjs firebase firebase-realtime-database react-router


【解决方案1】:

在您的回调中,this 指针不再指向您的 React 组件。有很多方法可以解决这个问题:

this 捕获到另一个变量中

var component = this;
query.on("child_added", function hello (snapshot) {
    ...
    component.props.router.push('Index');
});

显式绑定this

query.on("child_added", function hello (snapshot) {
    ...
    this.props.router.push('Index');
}).bind(this);

使用粗箭头,隐式保留this

query.on("child_added", snapshot => {
    ...
    this.props.router.push('Index');
});

请注意,这是开发人员在 JavaScript 中遇到的一个非常常见的问题,我强烈建议您详细了解 this 在回调中的行为方式:

【讨论】:

    猜你喜欢
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 2016-01-01
    • 2021-11-15
    相关资源
    最近更新 更多