【问题标题】:Can I use a dumb component as my top-level component with React/Redux App?我可以在 React/Redux App 中使用哑组件作为我的顶级组件吗?
【发布时间】:2018-08-07 20:05:34
【问题描述】:

我有以下设置:

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。然后将那些连接的组件视为顶部连接的组件。这样做有什么问题吗?

【问题讨论】:

  • 我没有看到任何问题,但也不明白它的目的
  • 你能用更多关于路由嵌套背后的推理的信息来更新这个问题吗?因为据我所知,在 react router v4 之后,就不再需要 Route 嵌套了。

标签: reactjs redux react-redux components


【解决方案1】:

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

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

并将您的操作和 redux 状态映射到组件的道具。组件只需要是 store 的 Provider 的子级即可。

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>

【讨论】:

    【解决方案2】:

    你可以这样做,没问题。

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

    【讨论】:

      【解决方案3】:

      您绝对可以让愚蠢的组件包装智能组件,只是为了为其子组件定义布局。通常,最好的方法是让虚拟 DOM 树的叶子连接到存储,这样更容易检查状态的变化,并且只在真正需要时触发render

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-22
        • 2020-04-05
        • 1970-01-01
        • 1970-01-01
        • 2021-12-08
        • 2022-11-17
        • 2017-02-14
        • 1970-01-01
        相关资源
        最近更新 更多