异步获取JSON然后呈现组件

时间:2017-05-27 22:38:50

标签: javascript json reactjs promise

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

我对React很新,曾经是开发者。在Angular中,我曾经使用生命周期钩子,例如ngOnInit / ngAfterViewInit(获取一些JSON文件,然后在迭代函数中午餐)。我怎样才能在React中实现它?是否可以使用生命周期钩子来访问它,例如ComponentWillMountComponentDidMount

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

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?

非常感谢你。

2 个答案:

答案 0 :(得分: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,但您可能需要使用<noscript>代替null

这实际上阻止了组件在拥有所有数据之前进行渲染。

答案 1 :(得分:2)

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