首页 文章

如何使用React-Router和React-Redux将道具发送到子路由组件?

提问于
浏览
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这样的模块,但我想在没有它们的情况下做到这一点 . 如果有人知道如何做,请给我一些建议,我们将非常感激 .

1 回答

  • 4

    如果您希望树中的某些组件接收Redux的状态数据,则必须使用React-Redux库的 connect() 函数将它们设为"container components" .

    例如,您可以像这样写一个“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中找到有关容器组件的详细信息 .

相关问题