Javascript 如何从url获取json并在js页面上显示json内容

Javascript 如何从url获取json并在js页面上显示json内容,javascript,reactjs,fetch,microsoft-teams,Javascript,Reactjs,Fetch,Microsoft Teams,我正在制作一个定制的微软团队应用程序,在这个应用程序中,我试图从一个url获取一个json,然后稍后显示内容。但是,获取失败。我的目标是从提供的url获取数据列表,然后将其显示在我的团队应用程序的选项卡中,该选项卡将显示在以下位置: 正如你可能知道的,我根本没有javascript方面的经验,但是定制的MS teams应用程序需要javascript // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed

我正在制作一个定制的微软团队应用程序,在这个应用程序中,我试图从一个url获取一个json,然后稍后显示内容。但是,获取失败。我的目标是从提供的url获取数据列表,然后将其显示在我的团队应用程序的选项卡中,该选项卡将显示在以下位置:

正如你可能知道的,我根本没有javascript方面的经验,但是定制的MS teams应用程序需要javascript

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import React from 'react';
import './App.css';
import * as microsoftTeams from "@microsoft/teams-js";

/**
 * The 'GroupTab' component renders the main tab content
 * of your app.
 */

class Tab extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      context: {}
    }
  }

  //React lifecycle method that gets called once a component has finished mounting
  //Learn more: https://reactjs.org/docs/react-component.html#componentdidmount
  componentDidMount(){
    // Get the user context from Teams and set it in the state
    microsoftTeams.getContext((context, error) => {
      this.setState({
        context: context
      });
    });
    // Next steps: Error handling using the error object
  }

  componentDidMount() {
    fetch('http://example.com/movies.json')
      .then(response => response.json())
      .then(data => console.log(data));

  }

  render() {
      var jsondata = data; 
      let userName = Object.keys(this.state.context).length > 0 ? this.state.context['upn'] : "";

      return (
        <div>

        </div>
      );
  }
}
export default Tab;
//版权所有(c)微软公司。版权所有。
//根据麻省理工学院许可证授权。
从“React”导入React;
导入“/App.css”;
从“@microsoft/teams js”导入*作为MicrosoftTeam;
/**
*“GroupTab”组件呈现主选项卡内容
*你的应用程序。
*/
类选项卡扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
上下文:{}
}
}
//组件安装完成后调用的React生命周期方法
//了解更多信息:https://reactjs.org/docs/react-component.html#componentdidmount
componentDidMount(){
//从团队获取用户上下文并将其设置为状态
microsoftTeams.getContext((上下文,错误)=>{
这是我的国家({
上下文:上下文
});
});
//下一步:使用错误对象处理错误
}
componentDidMount(){
取('http://example.com/movies.json')
.then(response=>response.json())
.then(data=>console.log(data));
}
render(){
var jsondata=数据;
让userName=Object.keys(this.state.context).length>0?this.state.context['upn']:“”;
返回(
);
}
}
导出默认选项卡;
总之,如何从url获取json并在团队内的tab.js页面上显示json的内容


提前感谢您的帮助。

虽然我无法说明Teams API是如何工作的,但我可以帮助您了解如何在react组件中从json API呈现内容

componentDidMount
函数中,您的示例发送和接收来自API的响应。要呈现此响应,我们需要将
数据
分配给组件的“状态”,然后使用它以HTML呈现

这将非常简单。首先,您需要扩展组件的状态,方式与您在
上下文中所做的类似。首先在构造函数中执行此操作,其中我们将声明空对象的初始状态(我将其命名为
content
,但您可以使用任何最有意义的名称):

在React中,我们使用
setState
在某些内容发生更改时更新此状态对象状态,例如在
componentDidMount
等生命周期方法上。当您想将状态对象从初始值更改为其他值时,只需再次调用此
setState
。在我们的例子中,当我们从API接收数据时

setState
接受您提供的任何内容,并将其合并到state对象中,因此您只需声明任何要更改的内容。任何未声明的内容将保持不变

因此,在
componentDidMount
中,我们可以做一些小的更改,以便在数据到达时对其进行处理:

 componentDidMount() {
    fetch('http://example.com/movies.json')
      .then(response => response.json())
      .then(data => {
        this.setState({
          content: data 
        })
      });
  }
这基本上是说:

  • 安装组件后,调用从API获取
  • 然后,通过该响应,从主体中获取json
  • 然后,在
    content
    键下将json“data”分配到组件的状态对象中
然后,您可以通过调用
this.state.content
来处理这些数据。我不确定数据将采用何种格式,但从API返回的任何json对象都将存储在
this.state.content

例如,假设我们从API中得到一个简单的对象,看起来像这样
{title:“tabtitle”}
。这意味着,成功调用API后,我们的状态对象将如下所示:

{
  context: "whatever you have here", // whatever you have here, I don't know this
  content: { title: "Tab title" }
}
更新此状态对象时,react将触发组件的新渲染

因此,为了让它出现在我们的组件中,我们需要在
render
函数中使用这个状态(如果需要动态渲染而不是硬编码,我们会用大括号将它们括起来):

render(){
返回(
//…你的其他职能
{this.state.content.title}
);
}
正如您可能猜到的,如果标题存在,这将在div中显示标题

<>最后,您应该考虑在API调用本身解决之前处理组件的状态。生命周期方法
componentDidMount
将在装入组件后调用,因为您正在访问一个API,所以在API调用自行解析之前,将有一些内容呈现给DOM。在我的示例中,它将只是一个空div,然后当状态更新并且再次调用render函数时,它将出现

您可以通过扩展state对象来查看API响应是否完成(您可以在设置内容的同一位置更新它),从而更有效地实现这一点,并且可以有条件地在此基础上呈现UI

关于生命周期的方法将帮助您更了解此模式


祝你好运

好吧,你可以信赖@Josh Vince的解释,因为他做得很好,我只需要为你编写更简洁的代码

让我们创建两个方法,用各自的数据设置状态,然后简单地调用状态值,并根据您的意愿呈现以下内容

import React, {Component} from 'react';
import './App.css';
import * as microsoftTeams from "@microsoft/teams-js";

class Tab extends Component {
    this.state = {
      context: {},
      movies: null
    }

     getContext = () => {
      try {
         microsoftTeams.getContext((context) => this.setState({context}));
       }
      catch(error){
        console.log('ERROR ->', error);
        throw error;
      }
     }

      fetchMoviesData = () => {
        try {
           fetch('http://example.com/movies.json')
           .then(response => response.json())
           .then(data => this.setState({movies: data}));
        } catch(error){
           console.log('ERROR ->', error);
           throw error;
        }
      }

  componentDidMount() {
     this.getContext();
     this.fetchMoviesData();
  }

  render() {
      let {movies, context} = this.state;
      const jsondata = movies; 
      let userName = Object.keys(this.state.context).length ? context['upn'] : "";
      return <>JSONDATA: {jsondata}, USERNAME: {userName}</>
  }
}
export default Tab;
import React,{Component}来自'React';
导入“/App.css”;
从“@microsoft/teams js”导入*作为MicrosoftTeam;
类选项卡扩展组件{
此.state={
上下文:{},
电影:空
}
getContext=()=>{
试一试{
getContext((context)=>this.setState({context}));
}
捕获(错误){
console.log('ERRO
render() {
  return (
      //... the rest of your function
      <div>{this.state.content.title}</div>
  );
}

import React, {Component} from 'react';
import './App.css';
import * as microsoftTeams from "@microsoft/teams-js";

class Tab extends Component {
    this.state = {
      context: {},
      movies: null
    }

     getContext = () => {
      try {
         microsoftTeams.getContext((context) => this.setState({context}));
       }
      catch(error){
        console.log('ERROR ->', error);
        throw error;
      }
     }

      fetchMoviesData = () => {
        try {
           fetch('http://example.com/movies.json')
           .then(response => response.json())
           .then(data => this.setState({movies: data}));
        } catch(error){
           console.log('ERROR ->', error);
           throw error;
        }
      }

  componentDidMount() {
     this.getContext();
     this.fetchMoviesData();
  }

  render() {
      let {movies, context} = this.state;
      const jsondata = movies; 
      let userName = Object.keys(this.state.context).length ? context['upn'] : "";
      return <>JSONDATA: {jsondata}, USERNAME: {userName}</>
  }
}
export default Tab;