reactjs – 使用React Router在Redux React应用程序中传递道具
发布时间:2020-12-15 20:19:07 所属栏目:百科 来源:网络整理
导读:这是我的入口点文件: 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/createBrowse
这是我的入口点文件:
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 libs … 编辑: 我更改了仪表板组件以将其包含在底部: Dashboard.propTypes = { authActions: PropTypes.object.isRequired,mapDispatchToProps)(Dashboard) 我现在可以访问Redux状态和操作.我不确定这是不是正确的方法,但它现在有用…… 解决方法
使用react-router v1,您可以使用以下命令访问最深的当前路由上的props:this.props.route.
<Route path='/' component={App}> <IndexRoute component={Home} /> <Route path='about' component={About} /> <Route path='dashboard' component={Dashboard} customprop="Hello,it's me" /> <Route path="*" component={NoMatch} /> </Route> 在仪表板组件中: this.props.route.customprop => “你好,这是我” 要访问当前路径树中的所有路径,可以遍历this.props.routes(最深路径是最后一个). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |