如果没有显示任何错误,'push'不起作用

时间:2016-08-30 13:20:12

标签: reactjs redux react-router-redux

我想要的是在用户点击按钮时更改路线。

代码与real-world示例非常相似,并遵循react-router-redux中介绍的所有步骤。

减速器/ index.js

import { combineReducers } from 'redux'
import { routerReducer as routing } from 'react-router-redux'
import entities from './entities'


const rootReducer = combineReducers({
  entities,
  routing
})

export default rootReducer

index.js

import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import browserHistory from 'react-router/lib/browserHistory'
import syncHistoryWithStore from 'react-router-redux/lib/sync'
import Root from './src/web/containers/Root'
import configureStore from './src/store/configureStore'

const store = configureStore()
const history = syncHistoryWithStore(browserHistory, store)

render(
  <Root store={store} history={history} />,
  document.getElementById('root')
)

Root.js

import React, { Component, PropTypes } from 'react'
import { Provider } from 'react-redux'
import routes from '../routes'
import Router from 'react-router/lib/Router'

export default class Root extends Component {
  render() {
    const { store, history } = this.props
    return (
      <Provider store={store}>
        <div>
          <Router history={history} routes={routes} />
        </div>
      </Provider>
    )
  }
}

Root.propTypes = {
  store: PropTypes.object.isRequired,
  history: PropTypes.object.isRequired
}

routes.js

import React from 'react'
import Route from 'react-router/lib/Route'
import App from './containers/App'

export default (
  <Route path="" component={App}>
    {/* Other routes */}
  </Route>
)

configureStore.js

import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from '../reducers'
import { apiMiddleware } from 'redux-api-middleware';
import {routerMiddleware, routerReducer} from 'react-router-redux'
import browserHistory from 'react-router/lib/browserHistory'

const createStoreWithMiddleware = applyMiddleware(apiMiddleware)    (createStore);


export default function configureStore(preloadedState) {
  const store = createStore(
    rootReducer,
    preloadedState,
    compose(
      applyMiddleware(
        apiMiddleware,
        routerMiddleware(browserHistory),
        thunk,
      ),
    )
  )

  return store
}

然后我想在这样的页面中使用push

import { push } from 'react-router-redux'
class Test extends Component {
  render() {
    return (
      <button onClick={()=>push('/path')}>Test</button>
    )
  }
}

但没有任何事情发生,没有显示错误。

1 个答案:

答案 0 :(得分:1)

问题似乎是你的组件'测试'。

您必须向该组件提供商店的调度功能,以便推送进行更改。

import { push } from 'react-router-redux';
import { connect } from 'react-redux';

@connect()
class Test extends Component {
  render() {
    // Provide component with dispatch function
    const { dispatch } = this.props;

    return (
      <button onClick={() => dispatch(push('/path'))}>
        Test
      </button>
    )
  }
}

navigation-events-via-redux-actions