【问题标题】:How to reduce react-redux boilerplate - I try creating a ComponentFactory but I'm getting react-redux errors如何减少 react-redux 样板 - 我尝试创建一个 ComponentFactory 但我收到 react-redux 错误
【发布时间】:2016-11-09 11:28:01
【问题描述】:

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

谢谢。

【问题讨论】:

  • 您的标题与您的问题完全无关。你问了一个关于如何修复错误的问题,并在最后抛出“我怎样才能减少样板文件”。

标签: javascript reactjs react-native redux react-redux


【解决方案1】:

如果您使用实际的组件类,一切都会变得更简单,而不是尝试扩展空连接的类 (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);

【讨论】:

  • 这实际上看起来不错,但是有没有办法在父组件的构造函数上运行东西呢?这是我忘记提及的事情,但我需要它。
  • 我想我不明白“父组件”是什么。
  • 好吧,假设我希望我的子组件始终在它的构造函数中运行一些样板代码,如下所示: class Child extends React.Component { constructor(props){ /*do something here*/ } }我可以为我使用您的建议创建的每个孩子一遍又一遍地跳过写作吗?也许通过在createScreen 方法中添加样板代码?
  • 这真的取决于你想做什么,但是在组件之间共享行为最好用higher order component来处理。
  • 绝对精彩!谢谢你的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-22
  • 1970-01-01
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多