我想创建一个名为createScreen
的工厂函数,用于减少react-redux
所需的样板。
看起来像这样:
ParentScreenFactory.js
export default function createScreen(stateActions = []) {
class ParentScreen extends React.Component {
}
function mapStateToProps(state) {
return {
...state,
};
}
function mapDispatchToProps(dispatch) {
const creators = Map()
.merge(...stateActions)
.filter(value => typeof value === 'function')
.toObject();
return {
actions: bindActionCreators(creators, dispatch),
dispatch,
};
}
return connect(mapStateToProps, mapDispatchToProps)(ParentScreen);
}
Child.js
const ParentScreen = createScreen([
routingActions,
authActions,
]);
class Child extends ParentScreen {
constructor(props) { // <-- error on this line
super(props);
}
render() {
return (
<View/>
);
}
}
export default Child;
出于某种原因,我得到了undefined is not an object (evaluating 'context.store')
。
堆栈跟踪:
Connect(ParentScreen)
connect.js:129
这是代码行_this.store = props.store || context.store;
。
你在这看到任何明显的错误?
除此之外,您对如何减少所有样板代码有更好的了解吗?
谢谢。
答案 0 :(得分:2)
如果您使用实际的组件类,而不是尝试扩展空的连接组(this is the class you're actually extending),那么一切都会更简单。
如果您希望组件以可预测的方式工作,则需要直接连接组件。尝试从工厂返回一个功能。
export default function createScreen(stateActions = []) {
return (Component) => {
// ...
return connect(mapStateToProps, mapDispatchToProps)(Component);
};
}
然后你的实例化开始看起来像这样。
class Child extends React.Component {
// ...
}
const ParentScreen = createScreen([
routingActions,
authActions,
]);
export default ParentScreen(Child);
如果您想在所有组件之间共享某些行为,那么您最好使用更高阶的组件。
function withCommonBehaviour(Component) {
return (props) => {
let newProps = doSomething(props);
return <Component {...newProps} />;
};
}
然后将其挂钩在createScreen
函数中。
// ...
let CommonComponent = withCommonBehaviour(Component);
return connect(mapStateToProps, mapDispatchToProps)(CommonComponent);