这是我的入口点文件:
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 状态和操作。我不确定这是否是正确的方法,但它现在有效......