我已經制作了這個示例應用程序來學習如何使用react-router-dom和redux在一起,除了我看不到我如何可以訪問組件內的道具?使用react-router-dom和redux時從組件中訪問道具
所有的代碼是在這裏https://gist.github.com/kristiannissen/b9a9ef1904eb40af9c305e06af4cf0fc
入口文件index.js
import { render } from 'react-dom'
import React from 'react'
import { Provider } from 'react-redux'
import { ConnectedRouter } from 'react-router-redux'
import App from './app'
import { store, history } from './store'
render(
<Provider store={ store }>
<App />
</Provider>, document.getElementById('app'))
App.js
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import Main from './main'
import * as projectActions from './actions/project'
const mapStateToProps = (state) => {
return {
project: state.project
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({
...projectActions
}, dispatch)
}
const App = connect(mapStateToProps,
mapDispatchToProps)(Main)
export default App
main.js
import React from 'react'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
import {
combineReducers,
createStore,
compose,
applyMiddleware
} from 'redux'
import {
ConnectedRouter,
routerReducer,
routerMiddleware
} from 'react-router-redux'
import {
history,
store
} from './store'
const Home = ({ match }) => (
<div>Home</div>
)
const Tacos = ({ match }) => (
<div>
Tacos to order:
<Link to={`${match.url}/plain`}>Plain</Link>
<Link to={`${match.url}/cheese`}>Cheese</Link>
<Link to={`${match.url}/chipotle`}>Chipotle</Link>
<div>
<Route path={`${match.url}/:kind`} component={ Taco } />
</div>
</div>
)
const Taco = ({ match }) => (
<div>You ordered {match.params.kind}</div>
)
const Main = (props) => (
<ConnectedRouter history={ history }>
<div>
<Link to="/">Home</Link>
|
<Link to="/tacos">Tacos</Link>
<div>
<Route path="/" component={ Home } {...props}/>
<Route path="/tacos" component={ Tacos } {...props}/>
</div>
</div>
</ConnectedRouter>
)
export default Main
store.js
import createHistory from 'history/createHashHistory'
import {
createStore,
compose,
applyMiddleware
} from 'redux'
import {
routerMiddleware
} from 'react-router-redux'
import rootReducer from './reducers/index'
import { project } from './data'
const initialState = {
project
}
export const history = createHistory()
export const store = createStore(rootReducer,
initialState, compose(
applyMiddleware(routerMiddleware(history))
))
我認爲這些是設置最重要的文件。我的問題是,如何從我的Taco組件中訪問我的動作中的props.newProject()函數?使用React開發者工具,我可以看到我的路由器可以訪問props.newProject(),但它不在Taco級別。
我應該使用{...}道具的道具傳遞給塔克組件或者是有一個更聰明的方式?
我用https://github.com/ReactTraining/react-router/tree/master/packages/react-router-redux以及https://reacttraining.com/react-router/web/example/preventing-transitions作爲參考。
如果你想在一個組件中使用一個動作,那基本上是'connect'的意思。你已經爲'App'完成了,如果你想使用該組件的動作,你還需要爲'Taco'組件做同樣的事情。 –
@MarioF看起來怎麼樣?對於每個想要訪問的組件,都使用connect()(Taco)等等?這接縫像很多額外的工作 –
我的意思是你可以連接組件,並從狀態獲得你想要的屬性,或連接一個父組件,並將信息作爲道具傳遞給兒童 –