如何减少 react-redux 样板 - 我尝试创建一个组件工厂,但我收到 react-redux 错误



我想到创建一个名为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;。这里有什么明显的错误吗?除此之外,你对如何减少这些样板代码有更好的想法吗?

谢谢。

如果您使用实际的组件类,而不是尝试扩展空的连接类(这是您实际扩展的类),一切都会更简单。

如果你想让你的组件可预测地工作,那么你需要直接连接你的组件。试着从你的工厂返回一个函数。

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);

最新更新