javascript - 如何调用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',
}]}
解决方案
在渲染函数中,我使用了 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;
});
推荐阅读
- python - 如何将 repr(str) 的结果返回给 str?
- java - 我无法在 Heroku 上部署 Springboot
- ruby - 使用 Ruby 的 Nokogiri 解析 XML 文档时出错
- macos - 从自定义 URL 方案启动使用 Unity 创建的 OSX 应用程序
- c++ - 创建类对象然后调用函数与使用具有范围解析运算符的静态函数的性能差异
- javascript - 为什么 isFinite() 对包含数字的字符串返回 true?
- mysql - 从准备好的语句中获取结果到变量中
- .htaccess - js 文件未在 chrome 中加载(隐身窗口)
- javascript - 为什么 nuxt generate full static 不会在某些页面中提取有效负载?
- c# - 在 C# 中调用库扩展方法之前应用条件