如果这个组件是并且将是唯一一个使用连接状态和操作的组件,不,这不是一个坏的做法。即使不是这样,也可以将多个组件连接到存储区。但是,使用容器组件并将所需的状态部分和一些动作创建者传递给相关的子组件并不容易吗?
import React from "react";
import ReactDOM from "react-dom";
import { connect } from "react-redux";
import { anAction, anotherAction } from "./actions/";
class ContainerApp extends React.Component {
state = {
maybeSomeLocalState: "",
}
render() {
const { aState, anAction, anotherState, anotherAction } = this.props;
return (
<div>
<Child
aState={aState}
anAction={anAction}
/>
<Child2
anotherState={anotherState}
anotherAction={anotherAction}
/
</div>
);
}
}
const mapStateToProps = state => ({
aState: state.aState,
anotherState: state.anotherState,
});
export default connect( mapStateToProps, { anAction, anotherAction } )(ContainerApp);
const Child = (props) => (
<div>
<p>{props.aState.someValue}</p>
<button onClick={props.anAction}>Do something</button>
</div>
);
const Child2 = (props) => (
<div>
<p>{props.anotherState.someValue}</p>
<button onClick={props.anotherAction}>Do another thing</button>
</div>
);