【问题标题】:Getting a JSON asynchronously and THEN rendering the component异步获取 JSON 并渲染组件
【发布时间】:2017-10-28 13:35:35
【问题描述】:

我有一个组件,它必须下载一个 JSON 文件并然后对其进行迭代并在屏幕上显示 JSON 中的每个元素。

我对 React 有点陌生,以前是 ng dev。在 Angular 中,我曾经使用生命周期钩子来做这件事,例如ngOnInit/ngAfterViewInit(获取一些 JSON 文件,然后午餐迭代函数)。我如何在 React 中实现它?是否可以通过生命周期钩子来访问它,例如 ComponentWillMount 或 ComponentDidMount。

我的代码(肯定是错的):

export default class ExampleClass extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      data: [],
    }
  }

  componentWillMount(){
    getData();
  }

  render() {   
    return (
      <ul>
        {this.state.data.map((v, i) => <li key={i}>{v}</li>)}
      </ul>
    )

  };
}

const getData = () => {
  axios.get(//someURL//)

    .then(function (response) {
      this.setState({data: response.data});
    })
    .catch(function (error) {
      console.log(error);
    })
};

如何在渲染组件之前强制 React 获取 JSON?

非常感谢。

【问题讨论】:

标签: javascript json reactjs promise


【解决方案1】:

在ComponentWillMount 中发出 AJAX 请求有效。 https://facebook.github.io/react/docs/react-component.html#componentwillmount

您也可以根据您的具体需求将该逻辑应用到您的构造函数中。 https://facebook.github.io/react/docs/react-component.html#constructor

export default class ExampleClass extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      data: [],
    }
    axios.get(/*someURL*/)
      .then(function (response) {
        this.setState({data: response.data});
      })
      .catch(function (error) {
        console.log(error);
      })
  }
}

【讨论】:

  • 这很奇怪,但是当我使用componentWillMount时,我无法将返回的obj分配给任何变量,因为完成时不存在变量......
  • @H.Doe 我不明白你在说什么,请编辑你的问题,举例说明“不存在变量”的含义。
【解决方案2】:

您可以在渲染函数中执行简单的if 语句。

render () {
  if (Boolean(this.state.data.length)) {
    return <ul>{this.state.data.map((v, i) => <li key={i}>{v}</li>)}</ul>
  }
  return null
}

你也可以使用更高阶的组件来做同样的事情。

const renderIfData = WrappedComponent => class RenderIfData extends Component {
  state = {
    data: []
  }
  componentWillMount() {
    fetchData()
  }
  render() {
     if (Boolean(this.state.data.length)) {
       return <WrappedComponent {...this.state} />
     }
    return null
  }
}

然后你可以用 HOC 包裹表现层。

renderIfData(ExampleClass)

不确定您使用的是什么版本的 React,但您可能需要使用 &lt;noscript&gt; 而不是 null。

这实际上是在阻止您的组件在获得所有数据之前进行渲染。

【讨论】:

    猜你喜欢
    • 2015-01-27
    • 2022-01-15
    • 2018-09-03
    • 2019-07-21
    • 2023-03-26
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多