我正在使用React + React-Router和React-redux创建网站。这是我的商店和减速机:
const defaultState = {
posts: [{key:0, title: 'Default post', text: 'Every visitor is welcome!'}]
};
const store = createStore(
(state = defaultState, action) => {
switch(action.type) {
default:
return state;
}
}
);
我还没有任何动作,我稍后会添加它。但是,回到这一点,这是App Component,它是React App的入口点。
const App = React.createClass({
render() {
return (
<div>
<h1>React Router + Redux Blog</h1>
<ul>
<li><IndexLink to="/">Main</IndexLink></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/posts">Posts</Link></li>
</ul>
{this.props.children}
</div>
);
}
});
此App组件将与Redux-Router的连接方法连接:
const ConnectedApp = connect( (state) => {
return {
posts: state.posts
};
})(App);
现在,最后,我将在Provider内部提供Router组件而不是ConnectedApp,并使用ConnectedApp作为索引组件。
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={ConnectedApp}>
<IndexRoute component={Main} />
<Route path="about" component={About} />
<Route path="posts" component={Posts} >
<IndexRoute component={PostsMain} posts={[]} />
<Route path="write" component={PostsWrite} />
</Route>
</Route>
</Router>
</Provider>,
document.getElementById('app')
);
现在,这就是问题所在。我想将Redux Store状态作为Props发送到子组件(PostsMain或PostsWrite),但我不知道如何传递它。可能呈现的每个子组件都由React Router决定,并且Redux没有任何存储状态。
我看到了一些像React-Router-Redux,Redux-Router这样的模块,但我想在没有它们的情况下做到这一点。如果有人知道该怎么做,请给我一些建议,我们将非常感激。
答案 0 :(得分:4)
如果您希望树中的某些组件接收Redux的状态数据,则必须使用React-Redux库的connect()
函数将它们设为“容器组件”。
例如,您可以像这样写一个“PostsMain”容器:
import { connect } from 'react-redux';
import PostsMainComponent from '../components/posts_main_component.jsx';
const mapStateToProps = (state) => {
return {
// the desired props calculated from the store's state, for example:
posts: state.posts,
};
};
const PostsMainContainer = connect(
mapStateToProps,
)(PostsMainComponent);
export default PostsMainContainer;
然后在路线声明中使用它,如下所示:
<IndexRoute component={PostsMainContainer} />
您可以在Redux's doc以及Dan Abramov的post中找到有关容器组件的详细信息。