简体   繁体   中英

react-router-redux, push method does not work

I am using react-router-redux.

I don't know how to create the demo to describe the issue simply. I push all code on Github. https://github.com/jiexishede/newReactSOAskDemo001

The a-href work well. @ https://github.com/jiexishede/newReactSOAskDemo001/blob/ask1/src/components/Home/Preview.js/#L37

Now, the push method does not work.
@ https://github.com/jiexishede/newReactSOAskDemo001/blob/ask1/src/components/Home/Preview.js/#L30

I edit the code and update it on GitHub.

I import the hashHistory .

https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L9

hashHistory.push('detail/'+id); work well. https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L32

disPatchpush @ https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L31 It does not work.

In the Home.js :

  @connect(state => {
  return {
    list:state.home.list,

  };
}, dispatch => {

  return {
    actions: bindActionCreators(actions, dispatch),
    dispatchPush:  bindActionCreators(push, dispatch),
  }
})

dispatchPush is passed from the Home.js to PreviewList to Preview .

Have your tried out?

handleClick(e) {
   e.preventDefault();
   this.props.history.push('/#/detail/' + id);

}

Tell me if it works or not and will update the answer accordingly.

Or if you want to try to navigate outside of components, try this .

Also try setting a route:

 <Route path="/preview" component={Preview} />

That might get you the history prop.

you miss routerMiddleware. Works beautifully after applying routerMiddleware.

import { browserHistory } from 'react-router';
import { routerReducer, routerMiddleware } from 'react-router-redux';
...
const finalCreateStore = compose(
  applyMiddleware(
      ThunkMiddleware, 
      FetchMiddleware, 
      routerMiddleware(browserHistory)
  ),
  DevTools.instrument(),
)(createStore);


const reducer = combineReducers({
  ...rootReducer,
  routing: routerReducer,
});

export default function configureStore(initialState) {
  const store = finalCreateStore(reducer, initialState);
  return store;
}

Read this section of the docs - https://github.com/reactjs/react-router-redux#what-if-i-want-to-issue-navigation-events-via-redux-actions

If you want to navigate to another route, try Proptypes, like so:

import React, { Component, PropTypes } from 'react';

class Preview extends Component {
        ...
  static contextTypes = {
    router: PropTypes.object
  };
  handleNavigate(id,e) {
    e.preventDefault();
    this.context.router.push(`/#/detail/${id}`);
  }
        ...
}

I had the same issue with react-router-redux and solved in the following way.

There is need to use Router not BrowserRouter . The history object has to be created with the createBrowserHistory method imported from history package.

Then the history has to be synchronized with the store using syncHistoryWithStore method imported from react-router-redux . This new history object will be passed to Router .

Then initialize the routerMiddleware passing to it the synchronized history object.

Please check out this code:

store.js

import createSagaMiddleware from 'redux-saga';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { routerReducer, routerMiddleware as reduxRouterMiddleware } from 'react-router-redux';
import { category, machine, machines, core } from './reducers';
import rootSaga from './sagas';

const rootReducer = combineReducers({
    category,
    machines,
    machine,
    core,
    routing: routerReducer,
});


const initStore = (history = {}) => {
    const sagaMiddleware = createSagaMiddleware();
    const routerMiddleware = reduxRouterMiddleware(history);

    const store = createStore(
        rootReducer, 
        applyMiddleware(
            sagaMiddleware, 
            routerMiddleware
        )
    );

    sagaMiddleware.run(rootSaga);

    return store;
}

export default initStore;

app.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router } from 'react-router';
import { Provider } from 'react-redux';
import { createBrowserHistory } from 'history';
import { syncHistoryWithStore } from 'react-router-redux';

import './index.css';
import App from './App';
import initStore from './store';
import * as serviceWorker from './serviceWorker';

const browserHistory = createBrowserHistory();

const store = initStore(browserHistory)
const history = syncHistoryWithStore(browserHistory, store);

ReactDOM.render(
    <Provider store={store}>
        <Router history={history}>
            <App />
        </Router>
    </Provider>,
    document.getElementById('root')
);

serviceWorker.unregister();

Connected React Router requires React 16.4 and React Redux 6.0 or later.

$ npm install --save connected-react-router

Or

$ yarn add connected-react-router

Usage Step 1

In your root reducer file,

Create a function that takes history as an argument and returns a root reducer. Add router reducer into root reducer by passing history to connectRouter. Note: The key MUST be router.

// reducers.js

import { combineReducers } from 'redux'
import { connectRouter } from 'connected-react-router'

const createRootReducer = (history) => combineReducers({
  router: connectRouter(history),
  ... // rest of your reducers
})
export default createRootReducer

Step 2

When creating a Redux store,

Create a history object. Provide the created history to the root reducer creator. Use routerMiddleware(history) if you want to dispatch history actions (eg to change URL with push('/path/to/somewhere')).

// configureStore.js

import { createBrowserHistory } from 'history'
import { applyMiddleware, compose, createStore } from 'redux'
import { routerMiddleware } from 'connected-react-router'
import createRootReducer from './reducers'
...
export const history = createBrowserHistory()

export default function configureStore(preloadedState) {
  const store = createStore(
    createRootReducer(history), // root reducer with router state
    preloadedState,
    compose(
      applyMiddleware(
        routerMiddleware(history), // for dispatching history actions
        // ... other middlewares ...
      ),
    ),
  )

  return store
}

Step 3

Wrap your react-router v4/v5 routing with ConnectedRouter and pass the history object as a prop. Remember to delete any usage of BrowserRouter or NativeRouter as leaving this in will cause problems synchronising the state. Place ConnectedRouter as a child of react-redux's Provider. NB If doing server-side rendering, you should still use the StaticRouter from react-router on the server.

// index.js

import { Provider } from 'react-redux'
import { Route, Switch } from 'react-router' // react-router v4/v5
import { ConnectedRouter } from 'connected-react-router'
import configureStore, { history } from './configureStore'
...
const store = configureStore(/* provide initial state if any */)

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}> { /* place ConnectedRouter under Provider */ }
      <> { /* your usual react-router v4/v5 routing */ }
        <Switch>
          <Route exact path="/" render={() => (<div>Match</div>)} />
          <Route render={() => (<div>Miss</div>)} />
        </Switch>
      </>
    </ConnectedRouter>
  </Provider>,
  document.getElementById('react-root')
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM