У меня есть простое приложение react-router-redux, где /home
есть кнопка, которая при нажатии должна перейти на страницу /profile
. В настоящее время мой код выглядит так.
действия/index.js
import { push } from 'react-router-redux'
import * as actionTypes from '../constants'
const homeClicked = () => {
return { type: actionTypes.HOME_CLICK }
}
const profileClicked = () => {
return { type: actionTypes.PROFILE_CLICK }
}
export const handleHomeClick = () => {
return (dispatch) => {
dispatch(homeClicked())
dispatch(push('/profile'))
}
}
export const handleProfileClick = () => {
return (dispatch) => {
dispatch(profileClicked())
dispatch(push('/'))
}
}
контейнеры/HomeContainer.js
import React from 'react'
import { connect } from 'react-redux'
import * as actions from '../actions'
import { withRouter } from 'react-router-dom'
import PropTypes from 'prop-types'
class Home extends React.Component {
handleClick = () => {
this.props.handleHomeClick();
}
render() {
return (
<div className='Home'>
<button onClick={this.handleClick}>Home</button>
</div>
)
}
}
Home.propTypes = {
handleHomeClick: PropTypes.func.isRequired
}
const mapStateToProps = () => {
return {}
}
export default withRouter(connect(mapStateToProps, actions)(Home))
контейнеры/ProfileContainer.js
import React from 'react'
import { connect } from 'react-redux'
import * as actions from '../actions'
import { withRouter } from 'react-router-dom'
import PropTypes from 'prop-types'
class Profile extends React.Component {
handleClick = () => {
this.props.handleProfileClick();
}
render() {
return (
<div className='Profile'>
<button onClick={this.handleClick}>Profile</button>
</div>
)
}
}
Profile.propTypes = {
handleProfileClick: PropTypes.func.isRequired
}
const mapStateToProps = () => {
return {}
}
export default withRouter(connect(mapStateToProps, actions)(Profile))
редукторы/index.js
import { HOME_CLICK, PROFILE_CLICK } from '../constants'
import { combineReducers } from 'redux'
import { routerReducer } from 'react-router-redux'
const clickReducer = (state={ message: 'HOME' }, action) => {
switch(action.type) {
case HOME_CLICK:
return { message: 'PROFILE' };
case PROFILE_CLICK:
return { message: 'HOME' };
default:
return state
}
}
export default combineReducers({
clicking: clickReducer,
routing: routerReducer
})
константы.js
export const HOME_CLICK = 'HOME_CLICK'
export const PROFILE_CLICK = 'PROFILE_CLICK'
история.js
import { createBrowserHistory } from 'history'
export default createBrowserHistory()
index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux';
import createRoutes from './routes'
import rootReducer from './reducers'
import thunk from 'redux-thunk'
import browserHistory from './history'
import reduxLogger from 'redux-logger'
import { createStore, applyMiddleware } from 'redux'
import { syncHistoryWithStore, routerMiddleware } from 'react-router-redux';
const middlewares = applyMiddleware(
thunk,
routerMiddleware(browserHistory),
reduxLogger
);
const store = createStore(rootReducer, middlewares)
const history = syncHistoryWithStore(browserHistory, store)
const routes = createRoutes(history)
ReactDOM.render(
<Provider store={store}>
{routes}
</Provider>,
document.getElementById('root')
)
маршруты.js
import React from 'react'
import { Router, Route, Switch } from 'react-router'
import HomeContainer from './containers/HomeContainer'
import ProfileContainer from './containers/ProfileContainer'
const createRoutes = (history) => {
return (
<Router history={history}>
<Switch>
<Route exact path='/' component={HomeContainer}/>
<Route path='/profile' component={ProfileContainer}/>
</Switch>
</Router>
)
}
export default createRoutes
app.js
import express from 'express'
import config from './config'
import path from 'path'
const app = express()
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')))
app.get('*', (req, resp) => {
resp.render('index');
})
app.listen(config.port, config.host, () => {
console.info('Server listening to', config.serverUrl())
})
Этот код изменяет URL-адрес, но не отображает страницу профиля при нажатии кнопки home
на главной странице. Также вот ссылка на изображение выходных данных регистратора избыточности.
Я застрял на этом в течение нескольких часов, и другие ответы SO не очень помогли. Любая помощь будет оценена по достоинству.
react-router-dom
. У них все еще есть экспортRouter
, поэтому вам не нужно использоватьBrowserRouter
. - person Chase DeAnda   schedule 21.10.2017react-router-dom
Иreact-router
?? Как это сработает? Вашroutes.js
используетreact-router
, но остальная часть приложения используетreact-router-dom
. Вы должны исправить файлroutes.js
, чтобы использоватьreact-router-dom
. - person Chase DeAnda   schedule 21.10.2017/profile
в адресной строке, работает? Роутер работает, но нет кнопки или вообще не работает маршрутизация? - person Chase DeAnda   schedule 21.10.2017react-router-dom
вместоreact-router
в вашем файлеroutes
? - person Chase DeAnda   schedule 21.10.2017react-router
из всех мест, но проблема осталась. - person tauoverpi   schedule 21.10.2017history.listen( (location, action) => {} )
, чтобы убедиться, что изменения истории происходят. Затем вы можете отладитьlocation
иaction
, чтобы убедиться, что они получают правильные входные данные. - person Chase DeAnda   schedule 21.10.2017action
, иaction
постоянно приходят какundefined
. Этого не может быть, верно? На самом деле я новичок в React и JS в целом. Так что извините, если я кажусь невежественным. - person tauoverpi   schedule 21.10.2017