首页 > 解决方案 > 如何调用rest api来获取json并在react js的下一个变量中使用它

问题描述

我正在构建一个基于 react js 的购物应用程序。我使用了来自https://codepen.io/paulkim/pen/oZLavq的示例应用程序,我想从 api 调用中获取产品 json。任何帮助。我尝试添加 jquery 并使用 api 调用:

const { reduxthunk } = ('redux-thunk');
//const middleware = applyMiddleware(promiseMiddleware());
//example
var return_first = async function () {

  var settings = {
    "url": "https://example.com",
    "method": "GET",
    "timeout": 0,
  };
  var tmp = null;

 await $.ajax(settings).done(function (response) {
    console.log(response);
    tmp = response.Items;
    console.log(response.Items)
  });
  return tmp;
}();

//需要来自先前jquery调用的股票值

const initialState = {
  cart: [],
  stock: [
    {
      id: 0,
      name: 'TC 2017 LS',
      description: 'VC FlexLight Jersey with spot sublimated Team Canada 2017 logo, from our Team Canada Collection.',
      price: 34.95,
      count: 12,
      img: 'https://cdn.shopify.com/s/files/1/0340/2849/products/TC2017_LS_Mens_grande.jpg?v=1485541617',
    }, {
      id: 1,
      name: 'TC 2017 Shorts',
      description: 'VC FlexLight Shorts with spot sublimated Team Canada 2017 logo, from our Team Canada Collection.',
      price: 25.00,
      count: 7,
      img: 'https://cdn.shopify.com/s/files/1/0340/2849/products/TC2017_Shorts_White_grande.jpg?v=1485541580',
    }]}

标签: javascriptreactjsreact-redux

解决方案


在渲染函数中,我使用了 Promise 来获取数据并动态渲染产品元素。

var temp=return_first;
//console.log(temp);
//console.log(temp);
apidata=temp.then(function(result) {
  console.log(result); // "Some User token"

// INITIAL STATE
const initialState = {
  cart: [],
  stock: result

};

  const store = Redux.createStore(reducers, initialState);
  ReactDOM.render(
    React.createElement(Provider, { store: store },
    React.createElement(App, null)),document.getElementById('app'));
  return result;
});




推荐阅读