【问题标题】:How to send props to sub routed-component with React-Router and React-Redux?如何使用 React-Router 和 React-Redux 将道具发送到子路由组件?
【发布时间】:2016-09-15 23:28:53
【问题描述】:

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

【问题讨论】:

    标签: reactjs react-router react-redux jsx react-router-redux


    【解决方案1】:

    如果您希望树中的某些组件接收 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 中找到有关容器组件的详细信息。

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 2017-11-06
      • 2017-01-28
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      相关资源
      最近更新 更多