我可以使用哑组件作为我的顶级组件与React / Redux App吗?

问题描述 投票:1回答:3

我有以下设置:

index.js

render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <Route component={App} />
        <Route component={Layout} >
            <Route path="/about-us" component={About} />
            <Route path="/" component={Home} />
        </Route>
    </ConnectedRouter>
  </Provider>,
  target
);

app.js

class App extends React.Component {

    render() {
        return (
            <div>
                {this.props.children}
            </div>
        );
    }
}

layout.js

class Layout extends React.Component {

    render() {
        return (
            <div>
                {this.props.children}
            </div>
        );
    }
}

然后我会为HomeAbout连接组件。我认为因为那些连接的组件与Route一起使用,所以他们可以访问高级别的store。然后将那些连接的组件视为顶部连接组件。这样做有什么问题吗?

reactjs redux react-redux components
3个回答
2
投票

要使用Redux,请将组件放在提供程序中

<Provider store={store}>
    [Components]  
</Provider>

并将您的动作和redux状态映射到组件的道具。组件只需要是商店提供商的子代。

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';    


const mapStateToProps = (state) => ({
    ...props: ...state.reducer.desired_props
})
const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        ...props: ...action_creator  // () => { type: '', payload: {} }
    }, dispatch)
}


const funcComp = (props) => {
    return (<div>{props.message}</div>)
}
const reduxReady = connect(mapStateToProps, mapDispatchToProps)(funcComp)


// or


class classyComp extends React.Component {
    render() {
        return (<div>{this.props.message}</div>)
    }
}
const alsoReduxReady = connect(mapStateToProps, mapDispatchToProps)(classyComp)

可以在任何地方

<Provider store={store}>
    <Anything>
        <reduxReady />
        <alsoReduxReady />
    </Anything>
</Provider>

1
投票

你可以做到这一点,没问题。

商店通过反应上下文(https://reactjs.org/docs/context.html)在组件层次结构中传播。所以一个组件会将redux存储的引用提供给它的所有子节点,即使它本身并不连接。


0
投票

你可以肯定有包含智能组件的哑组件,只是为他们的孩子定义一个布局。通常,最好的方法是让虚拟DOM树的叶子连接到商店,这样就可以更容易地检查状态的变化,并且只在真正需要时触发render

这是一篇关于这个主题的精彩帖子,来自Redux的合着者Dan Abramov:Presentational and Container Components

© www.soinside.com 2019 - 2024. All rights reserved.