2

我正在使用 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 的 connect 方法连接:

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,但我想不使用它们。如果有人知道怎么做,请给我建议,我们将不胜感激。

4

1 回答 1

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 的文档和Dan Abramov的这篇文章中找到有关容器组件的详细信息。

于 2016-05-19T08:31:41.683 回答