【发布时间】:2016-04-19 14:55:41
【问题描述】:
这是我的入口点文件:
import React, { PropTypes } from 'react'
import ReactDOM from 'react-dom'
import { createStore, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import { Router, Route } from 'react-router'
import { syncReduxAndRouter, routeReducer } from 'redux-simple-router'
import reducers from './reducers'
import App from './containers/app.jsx'
import About from './about.jsx'
import Dashboard from './dashboard/index.jsx'
const reducer = combineReducers(Object.assign({}, reducers, {
routing: routeReducer
}))
const store = createStore(reducer)
const history = createBrowserHistory()
syncReduxAndRouter(history, store)
const routes = {
path: '/',
component: App,
childRoutes: [
{ path: 'about', component: About },
{ path: 'dashboard', component: Dashboard }
]
}
ReactDOM.render(
<Provider store={store}>
<Router routes={routes} history={history} />
</Provider>,
document.getElementById('app')
)
从我能收集到的信息来看,这似乎是相当标准的。但是,我对如何将道具从App 降低到例如Dashboard 组件有点困惑。这是App 组件:
import React, {PropTypes} from 'react'
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import {Link} from 'react-router'
import * as authActions from './../actions/auth'
class App extends React.Component {
render() {
return (
<div>
<h1>App</h1>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/dashboard">Dashboard</Link>
</li>
</ul>
{this.props.children}
</div>
)
}
}
App.propTypes = {
authActions: PropTypes.object.isRequired,
authState: PropTypes.object.isRequired
}
function mapStateToProps(state) {
return {authState: state.authState}
}
function mapDispatchToProps(dispatch) {
return {
authActions: bindActionCreators(authActions, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
抱歉,代码不是更简洁,但我特别想将 authState(来自我的 Reducer)传递给 Dashboard 组件,我对它的工作原理有点困惑使用 React Router 和 redux-simple-router 库...
编辑:
我更改了Dashboard 组件以将其包含在底部:
Dashboard.propTypes = {
authActions: PropTypes.object.isRequired,
authState: PropTypes.object.isRequired
}
function mapStateToProps(state) {
return {authState: state.authState}
}
function mapDispatchToProps(dispatch) {
return {
authActions: bindActionCreators(authActions, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Dashboard)
我现在可以访问 Redux 状态和操作。我不确定这是否是正确的方法,但它现在有效......
【问题讨论】:
-
你使用的是什么版本的 react-router?你也可以用 jsx fyi 编写你的路由对象
-
@DominicTobias 1.0.2。是的,不过似乎更喜欢对象表示法!
标签: reactjs react-router redux react-router-redux