将道具传递到临时包装器

时间:2018-07-11 16:27:42

标签: reactjs react-router

我曾经在组件中获取数据,但是现在我了解了更高阶的组件,我试图将代码重构为使用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__)

withData:

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} />;
  }
 };
};

1 个答案:

答案 0 :(得分:0)

在那种情况下,您无需将任何内容传递给HOC,HOC只是一个返回React组件的函数。组件将收到道具,您可以通过this.props访问它们。通过this.props.match.url相同的方式访问URL。

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

赞:

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.