从URL反应获取JSON数据-格式问题

时间:2018-11-05 05:43:47

标签: javascript reactjs react-native jsonschema

我在一个问题中看到了有用的代码

getSchemaFromApiAsync() {
    return fetch('https://facebook.github.io/react-native/movies.json')
      .then(response => response.json())
      .then(responseJson => {
        return responseJson;
      })
      .catch(error => {
        console.error(error);
      });
  }

我有这个问题:我想将我的responseJson作为js对象获取,或将其隐藏到js对象中。我尝试了JSON.stringify,但没有用。有什么想法吗?

3 个答案:

答案 0 :(得分:0)

您的返回值是promise函数

constructor(props) {
    super(props);
    this.state = {};
}

componentWillMount(){
    this.getObject();
}

getObject(){
    return fetch('https://facebook.github.io/react-native/movies.json')
      .then(response => response.json())
      .then(responseJson => {
          this.setState({responseJson : responseJson});
         return responseJson;
      })
      .catch(error => {
        console.error(error);
      });
}

现在状态已设置。您可以在任何需要的地方访问此状态变量(也可以使用另一个组件)。

答案 1 :(得分:0)

使用ES6语法尝试此操作,希望您拥有支持此功能的最新库。

let getSchemaFromApiAsync = () => {
  return new Promise((resolve, reject) =>  {
     fetch('https://facebook.github.io/react-native/movies.json')
      .then(response => resolve(response.json()))
      .catch(error => {
        console.error(error);
        reject(error);
      });
    })
  }

  let main = async () => {
    let res = await getSchemaFromApiAsync();
    console.log("res", res);
  };

  main();

答案 2 :(得分:0)

尝试在相关的rest api中进行更改。在您的nodejs文件中使用json.stringyfy。 将您的json响应设置为作用域。