当前位置 : 主页 > 手机开发 > 无线 >

express – 在同构反应中检测移动

来源:互联网 收集:自由互联 发布时间:2021-06-10
我应该如何在reactjs express中实现检测移动设备?我使用 mobile-detect确定是否移动但首先我使用const md = new MobileDetect(window.navigator.userAgent)实现它,但我记得窗口在加载服务器时不存在.快递
我应该如何在reactjs express中实现检测移动设备?我使用 mobile-detect确定是否移动但首先我使用const md = new MobileDetect(window.navigator.userAgent)实现它,但我记得窗口在加载服务器时不存在.快递部分中的示例应该有效,因为这是我可以访问req的唯一地方,但是如何在我的反应应用程序中传递它以便以后使用?

UPDATE

// app.js

...
import { routes } from './routes';
import { match, RouterContext } from 'react-router';
import { renderToString } from 'react-dom/server';

...
const app = express();
app.use(express.static('public'));

app.set('view engine', 'ejs');

app.get('*', (req, res) => {
  // routes is our object of React routes defined above
  match({ routes, location: req.url }, (err, redirectLocation, props) => {
  if (err) { // something went badly wrong, so 500 with a message
    res.status(500).send(err.message);

  } else if (redirectLocation) { // we matched a ReactRouter redirect, so redirect from the server
    res.redirect(302, redirectLocation.pathname + redirectLocation.search);

  } else if (props) { // if we got props, that means we found a valid component to render for the given route
    const reducer = combineReducers(reducers);
    const store = applyMiddleware(...middlewares)(createStore)(reducer);

  ...
const server = http.createServer(app);
const port = process.env.PORT || 3003;

server.listen(port);
server.on('listening', () => {
  console.log('Listening on ' + port);
});

// client-render.js
import { routes } from './routes';
import { Router, browserHistory } from 'react-router'

ReactDOM.render(
  <Provider store={store}>
    <Router onUpdate={() => {scrollTop(); handleNotifs(store)}} routes={routes} history={browserHistory} />
  </Provider>,
  document.getElementById('app')
);

// routes.js
import AppComponent from './components/app';
import IndexComponent from './components/index';
...

const routes = {
  path: '',
  component: AppComponent,
  childRoutes: [{
    path: '/',
    component: IndexComponent,
    name: 'home'
  }, {...}]
}
通过使我的路由模块成为一个接受用户代理的功能,我完成了你所要求的.然后它只返回一个数组或嵌套的路由.这是一个例子……

routes.js

module.exports = (userAgent) => {
  const md = new MobileDetect(userAgent)
  if (md) { // not sure on the syntax of MobileDetect?
    return {
      // return mobile routes
    }
  } else {
    return {
      // return desktop routes
    }
  }
}

app.js

app.get('*', (req, res) => {
  match({ routes: routes(req.headers['user-agent']), location: req.url }, (err, redirectLocation, props) => {
    // continue as normal
  }
}

客户render.js

ReactDOM.render(
  <Provider store={store}>
    <Router onUpdate={() => {scrollTop(); handleNotifs(store)}} history={browserHistory}>
      {routes(navigator.userAgent)}
    </Router>
  </Provider>,
  document.getElementById('app')
);

另外,使用这种方法我们也可以将auth cookie传递给路由,这样如果路由落后于登录,onEnter方法可以重定向.

希望这可以帮助! BTW React-Router是最好的!!我得到了纽约的创作者,他们是一流的.

网友评论