繁体   English   中英

组件在ajax调用之前和之后呈现

[英]Component is rendering before and after ajax call

因此,我在代码学校毕业后从事我的第一个项目,并立即用我的ajax调用遇到麻烦。 看来我的渲染器正在ajax调用之前和之后渲染,因此当我尝试显示从数据库中获取的信息时出现错误

 import React, { Component } from 'react'; import $ from 'jquery'; class StepFive extends Component{ constructor(props) { super(props) this.state = { ingredients: [] } } ingredientsGrab() { var me = this; $.ajax({ method: 'GET', url: 'http://localhost:3002/api/ingredients', }) .then(function(ingredients){ me.setState({ingredients: ingredients}) }) } componentWillMount() { this.ingredientsGrab() } render() { console.log(this.state.ingredients[0], 'in render1') return( <div className='stepFiveBox'> <span>bubbly</span> </div> ) } } export default StepFive 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

在此处输入图片说明

当呈现组件,然后获取数据并使用此数据重新呈现该组件时,这是正常的行为。 但是为此,您应该使用componentDidMount

检查文档: https : //facebook.github.io/react/docs/react-component.html#componentdidmount

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM