Редуктор не улавливает действие LOCATION_CHANGE

Я работаю над тем, чтобы мое приложение React/Redux обновляло URL-адрес на основе действий. Я довольно много осмотрелся. Я думал, что у меня есть ручка, но, очевидно, я что-то упускаю. У меня есть другие редукторы, которые реагируют правильно.

В настоящее время я просто пытаюсь зарегистрировать действие.

Сокращение маршрутизации

const initialState = { locationBeforeTransitions: null };

export default function routing(state = initialState, action)
{
  switch (action.type)
  {
    case 'LOCATION_CHANGE':
      console.log(action)

    default:
      return state

  }

}

Магазин

/*
  Things from other people
 */

import { createStore, applyMiddleware, compose } from 'redux'
import { syncHistoryWithStore }                  from 'react-router-redux';
import { browserHistory }                        from 'react-router'
import   thunkMiddleware                         from 'redux-thunk'
import   createLogger                            from 'redux-logger'

/*
  Things from us
 */

import { fetchSuitesAndFails, fetchResults } from './actions/actions';
import   rootReducer                         from './reducers/index'

const enhancers = compose(
  window.devToolsExtension ? window.devToolsExtension() : f => f
);

const loggerMiddleware = createLogger()

/*
  Store
*/

export const store = createStore(
  rootReducer,
  enhancers,
  applyMiddleware(
    thunkMiddleware, // lets us dispatch() functions
    loggerMiddleware // neat middleware that logs actions
  )
);

// Export the history so we can keep track of things
export const history = syncHistoryWithStore(browserHistory, store);


/*
  Enable Hot Reloading for the reducers
  We re-require() the reducers whenever any new code has been written.
  Webpack will handle the rest
*/

if (module.hot) {
  // Enable Webpack hot module replacement for reducers
  module.hot.accept('./reducers/index', () => {
    const nextRootReducer = require('./reducers/index').default
    store.replaceReducer(nextRootReducer)
  })
}

Индекс

/*
  React router needs
*/
import { combineReducers } from 'redux'
import { routerReducer }   from 'react-router-redux'

/*
  Reducers
*/
import suite          from './suite'
import suitesandfails from './suitesandfails'
import routing        from './routing'


/*
  Put them all together and return a single reducer
*/
const rootReducer = combineReducers({
  suite,
  suitesandfails,
  routing,
  routing: routerReducer
})

export default rootReducer

person Will Luce    schedule 06.08.2016    source источник
comment
Вы добавили маршрутизацию в rootReducer?   -  person vijayst    schedule 06.08.2016
comment
Я сделал. Я обновил, чтобы показать.   -  person Will Luce    schedule 06.08.2016
comment
Какой код отправляет действие? Там может быть ошибка до редуктора.   -  person The Brofessor    schedule 06.08.2016
comment
Я никогда не назначал два редуктора одному и тому же свойству в CombineReducers. Первый редуктор не вызывается из-за двойного назначения? Хотя не уверен.   -  person vijayst    schedule 06.08.2016
comment
React-router-redux отправляет действие. Он отображается в инструментах разработчика.   -  person Will Luce    schedule 06.08.2016
comment
вы должны переименовать его.   -  person Kokovin Vladislav    schedule 06.08.2016
comment
Это правда, что я должен переименовать его, но все еще не играю в кости, когда я это делаю.   -  person Will Luce    schedule 06.08.2016


Ответы (2)


вы можете использовать строку "@@router/LOCATION_CHANGE", чтобы перехватить действие.

react-router-redux предоставляет const для этого

import { LOCATION_CHANGE } from 'react-router-redux'

....
case LOCATION_CHANGE:
      console.warn('LOCATION_CHANGE from your reducer',action)
      return state

ДЕМО-версия webpackbin

введите описание изображения здесь

код routerReducer из react-router-redux

person Kokovin Vladislav    schedule 06.08.2016

Вы также можете импортировать константу из файла 'react-router-redux'.

import { LOCATION_CHANGE } from 'react-router-redux'
 ...
 case LOCATION_CHANGE:
     console.warn('LOCATION_CHANGE from your reducer',action)
     return state
person Shane Daly    schedule 29.11.2016