【问题标题】:Passing props to hoc wrapper将道具传递给 hoc 包装器
【发布时间】:2018-07-11 16:27:42
【问题描述】:

我曾经在我的组件中获取数据,但现在我了解了更高阶的组件,我正在尝试重构我的代码以使用 hoc 来获取数据;

从原始组件如何将我从路由器道具获取的 url 移动到 hoc 包装器

 state = { details: [], loading: true };

 componentDidMount() {
  fetch(this.props.match.url)
   .then(res => res.json())
   .then(data => this.setState({ details: data, loading: false }))
}

我如何将this.props.match.url 传递给export default withData(App, __here__)?

与数据:

export const withData = (ComposedComponent, url) => {
  return class WithData extends Component {
  state = { data: [], loading: false };

  componentDidMount() {
    this.setState({ loading: true });
    fetch(url)
     .then(response => response.json())
     .then(data => this.setState({ loading: false, data }));
  } 

  render() {
    return <ComposedComponent {...this.state} {...this.props} />;
  }
 };
};

【问题讨论】:

  • 你能分享withData的代码吗?
  • 刚刚包含在问题中!

标签: reactjs react-router


【解决方案1】:

在这种情况下,您不需要向 HOC 传递任何内容,HOC 只是一个返回反应组件的函数。组件将收到道具,您可以通过this.props 访问它们。同样的方式访问urlthis.props.match.url。

最终,您正在渲染 HOC 针对特定路径返回的反应组件,因此组件将以相同的方式接收道具。

像这样:

export const withData = (ComposedComponent) => {
  return class WithData extends Component {

    state = { data: [], loading: false };

    componentDidMount() {
      this.setState({ loading: true });
      fetch(this.props.match.url);
       .then(response => response.json())
       .then(data => this.setState({ loading: false, data }));
    } 

    render() {
      console.log('this.props', this.props);
      return <ComposedComponent {...this.state} {...this.props} />;
    }

  };
};

Working Example.

【讨论】:

  • 哇!惊人的。我以为我必须将您的示例更改为fetch(url || this.props.match.url),但后来意识到这是同一回事哈哈。谢谢你!
  • 是的,但是 url 将只是您使用 Route 定义的路径,就像在我的示例中它将是 /info。
  • 很高兴为您提供帮助:)
猜你喜欢
  • 2020-08-09
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 2019-08-12
  • 2020-04-28
  • 2022-01-10
  • 2017-10-03
  • 2018-02-03
相关资源
最近更新 更多