【问题标题】:ReactJs - Access Wrapped State from HOC WrapperReactJs - 从 HOC Wrapper 访问包装状态
【发布时间】:2018-02-27 16:58:26
【问题描述】:

我尝试使用 HOC 模式而不是面向对象来避免冗余代码。

情况很简单,解释如下:

在主页我有这样的东西:

const WrappedComponent = Wrapper(Wrapped);
<WrappedComponent { ...this.props } />

在 Wrapper“组件”中,我想公开一个名为 foo_method 的方法,它是对 WebServer 的 Ajax 调用。结果必须以 Wrapped Component 的状态写入。

现在,WrappedComponent 可以调用 foo_method,但是当在 Wrapper 内部时,我没有 Wrapped 状态的范围,并且 this.props 包含 HomePage 的 props,而不是 wrapper,因此我无法在 Wrapper 中创建要调用的回调函数。

我在 HOC 的实现中忘记了什么吗?

【问题讨论】:

  • Wrapper 不能设置被包裹组件的状态,但它可以通过 props 传递结果。也可以通过 props 传递整个方法。

标签: reactjs


【解决方案1】:

我认为你的 HOC 应该看起来像这样,每个 WrappedComponent 都会在 props 中获得结果(加载时为 null,之后 API 响应),并且包装的组件可以通过 props.fetchFunction() 手动调用公开的 fetch 函数。

function Wrapper(WrappedComponent) {
    const fetchData = () => {
         return fetch('something');
    };

    return class extend React.Component {
        constructor(props) {
             super(props);
             this.state = {
                 result: null,
             };
        }
        componentDidMount() {
             fetchData().then((result) => {
                  this.setState({result});
             });
        }
        render() {
            return (
               <WrappedComponent
                   result={this.state.result}
                   fetchFunction={fetchData}
                   {...this.props}
               />
            );
        }
    }
}

【讨论】:

  • 谢谢。您的代码完美运行。我希望避免在 Wrapped 组件中使用componentWillReceiveProps,但我可以忍受它。
猜你喜欢
  • 1970-01-01
  • 2017-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多