Adding a base URL to an app using Redux-Router + React-Router

后端 未结 4 1561
孤独总比滥情好
孤独总比滥情好 2020-12-29 08:35

I\'m using React-Router 1.0.0-rc3 together with Redux-Router 1.0.0-beta3.

When using React-Router, you can use useBasename with createHistory

4条回答
  •  温柔的废话
    2020-12-29 08:56

    The API changes very often so this is what worked for me (I'm using the 2.0.3 version of redux-simple-router). I have defined the custom history in a separate file:

    import { useRouterHistory } from 'react-router'
    import { createHistory, useBasename } from 'history'
    import { baseUrl } from '../config'
    
    const browserHistory = useRouterHistory(useBasename(createHistory))({
      basename: "/appgen"
    });
    

    Now I need to initialize the store:

    import { syncHistory, routeReducer } from 'redux-simple-router'
    import browserHistory from '../misc/browserHistory'
    
    const rootReducer = combineReducers({
      // ...other reducers
      routing: routeReducer
    });
    
    const reduxRouterMiddleware = syncHistory(browserHistory);
    
    const finalCreateStore = compose(
      // ...other middleware
      applyMiddleware(reduxRouterMiddleware),
    )(createStore);
    
    
    const store = finalCreateStore(rootReducer, initialState);
    

    Eventually, you need to pass the history to the Router.

    import browserHistory from './misc/browserHistory'
    import routes from '../routes'
    
    export default class Root extends Component {
      static propTypes = {
        history: PropTypes.object.isRequired
      };
    
      render() {
        return (
          
            {routes}
          
        )
      }
    }
    

    Before I came up with this, I was using a manual solution. I defined my own Link component and my own redux action that were responsible for prepending the base URL. It might be useful for someone.

    Updated Link component:

    import React, { Component } from 'react'
    import { Link as RouterLink } from 'react-router'
    import { baseUrl } from '../config'
    
    export default class Link extends Component {
      render() {
        return 
      }
    }
    

    Custom action creator:

    import { routeActions } from 'redux-simple-router'
    import { baseUrl } from '../config'
    
    export function goTo(path) {
      return routeActions.push(baseUrl + '/' + path);
    }
    

    Updated root route:

    import { baseUrl } from './config'
    export default (
      
        //...nested routes
      
    );
    

    Note that these custom tools only support pushing updated paths, not the location descriptor object.

提交回复
热议问题