onBefore event on react-router

你离开我真会死。 提交于 2021-01-29 04:19:22

问题


Can I call Meteor method before react-router redirect me to a page? I would like to make a history of the logged-in user about his/her page views.

I see that in iron-router I can use onBeforeAction: function () {}

I cant find similar event handler for react-router of ReactTraining. I am searching in their docs, https://github.com/ReactTraining/react-router/tree/1.0.x/docs

In meteor server side, I am using simple:json-routes. I searched also their docs and can't find anything related to onBeforeAction event handler.

I am using react-router so I can't use iron-router at the same time. So Is there any way to log the page views of a logged-in user in Meteor-ReactJS


回答1:


Try to listen to the browser history browserHistory.listen

But first you have to detect the current location with getCurrentLocation




回答2:


Yes!

By :

  • encapsulating the redirection logic in one method AND
  • using a library for *event oriented programming like mufa

router-helper.js

import {browserHistory} from 'react-router' ; 
import {fire} from 'mufa';

export function redirect(to) {
     fire('onBeforeRedirect', to);
     browserHistory.push(to);
     fire('onAfterRedirect', to);
}

OtherFile-Subscribe-OnBefore.js

import {on} from 'mufa';

on('onBeforeRedirect', (to) => {
   //Your code here will be running before redirection .
});

Component-Call-Redirect.js

import {redirect} from 'router-helper';


 //...

  redirect('/profile'); //<-- This call will trigger also onBefore listeners


来源:https://stackoverflow.com/questions/42576444/onbefore-event-on-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!