我很難理解如何與react-router一起使用redux。如何將redux狀態傳遞給子路徑?
index.js
[...]
// Map Redux state to component props
function mapStateToProps(state) {
return {
cards: state.cards
};
}
// Connected Component:
let ReduxApp = connect(mapStateToProps)(App);
const routes = <Route component={ReduxApp}>
<Route path="/" component={Start}></Route>
<Route path="/show" component={Show}></Route>
</Route>;
ReactDOM.render(
<Provider store={store}>
<Router>{routes}</Router>
</Provider>,
document.getElementById('root')
);
App.js
import React, { Component } from 'react';
export default class App extends React.Component {
render() {
const { children } = this.props;
return (
<div>
Wrapper
{children}
</div>
);
}
}
Show.js
import React, { Component } from 'react';
export default class Show extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<ul>
{this.props.cards.map(card =>
<li>{card}</li>
)}
</ul>
);
}
}
這將引發
Uncaught TypeError: Cannot read property 'map' of undefined
我發現的唯一的解決辦法是改爲使用{}兒童這個:
{this.props.children &&
React.cloneElement(this.props.children, { ...this.props })}
這真的是這樣做的正確方法?
我認爲你不需要在每個組件中完成它,只需要你的頂層和路由處理程序組件。在你的例子中,Show是一個Route Handler,因此使用connect(這就是所謂的智能或容器組件)總的來說很好。它下面的所有組件(演示組件或啞組件)應該從Smart組件獲取它們的狀態作爲道具。 看看這裏:http://redux.js.org/docs/basics/UsageWithReact.html – woolagaroo
可以請你給一些簡單的例子,如何正確地做到這一點? – farukg