【发布时间】:2019-02-13 20:08:15
【问题描述】:
所以,我有一个 react 应用程序,我在其中使用多个 api 来获取一些数据,并且我正在尝试在其中开始使用 redux。我已经看过一些 redux 教程,但是当我开始考虑如何将这个 react 应用程序转换为 react-redux 时,我仍然有点困惑。就像如何将我使用的(this.setState)这样的东西转换为redux。我知道我必须使用 react-thunk 来开始在操作中获取这个 api,但我仍然很困惑。这是我的代码。
componentDidMount(){
let url = ``;
let url2 = ``;
fetch(url,{
method: 'GET'
})
.then((response)=> response.json())
.then((responseJson) => {
const newItems = responseJson.items.map(i => {
return{
name: i.name
};
})
const newState = Object.assign({}, this.state, {
items: newItems
});
console.log(newState);
this.setState(newState);
})
.catch((error) => {
console.log(error)
});
fetch(url2,{
method: 'GET'
})
.then((response)=> response.json())
.then((responseJson) => {
const newItems = responseJson.item.map(i => {
return{
img: i.img.url
};
})
const newarr = [...this.state.items, ...newItems];
var resObj = newarr.reduce(function(res, obj) {
for(var key in obj) {
if (obj.hasOwnProperty(key)) {
res[key] = obj[key];
}
}
return res;
}, {});
const newState = {
items: [resObj]
}
this.setState(newState);
})
.catch((error) => {
console.log(error)
});
}
【问题讨论】:
-
您的具体问题是什么?
标签: reactjs api redux react-redux fetch-api