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

时间:2018-02-28 02:45:01

标签: reactjs redux react-redux components

我有以下设置:

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

3 个答案:

答案 0 :(得分:2)

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

JSONArray list = new JSONArray();
JSONObject obj = new JSONObject(data)
JSONArray jsonArray = new JSONArray(obj);

for(int i=0;i<json.length();i++){
    JSONObject e = jsonArray.getJSONObject(i);
    String value = e.getString("Value"));
    list.put(value);
}

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

<Provider store={store}>
    [Components]  
</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)

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

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