在 React.js 中设置来自 axios 的存储对象
Setting store object from axios in React.js
我正在开发一个用 React.js 编写的应用程序,我从 JSON 提要中获取数据,然后我将在应用程序中以各种方式使用这些数据。
我通过 axios 调用提要:
module.exports = {
getMainPlaylist: function () {
var requestUrl = `${MAIN_PLAYLIST_FEED_URL}`;
return axios.get(requestUrl).then(function (res) {
return res.data.playlist
}, function (err) {
alert('error');
});
}
};
在我的 app.jsx 文件中,我有以下内容:
store.subscribe(() => {
var state = store.getState();
console.log('New state: ', state);
});
var mainPlaylist = MainPlaylistAPI.getMainPlaylist();
store.dispatch(actions.addMainPlaylist(mainPlaylist));
在我的动作文件中,我有这个:
export var addMainPlaylist = (mainPlaylist) => {
return {
type: 'ADD_MAIN_PLAYLIST',
mainPlaylist
}
};
在我的减速器文件中我有这个:
export var playlistReducer = (state = [], action) => {
switch (action.type) {
case 'ADD_MAIN_PLAYLIST':
return [
...state,
...action.mainPlaylist
];
default:
return state;
}
};
当我正常使用状态来获取数据时,它工作正常,但我认为因为我正在尝试将商店与 Web 服务一起使用,所以它可能因为异步过程而无法工作。
当我登录到控制台时,我得到这个:
console 1
console 2
我有 .NET 背景,所以我对只在 JavaScript 中工作还很陌生,我不知道从哪里开始解决这个问题。
感谢任何帮助!
我自己设法解决了这个问题。
Axios 是一个基于 promise 的客户端,所以我在调用它的地方使用了 .then()。
所以这个:
var mainPlaylist = MainPlaylistAPI.getMainPlaylist();
store.dispatch(actions.addMainPlaylist(mainPlaylist));
变成这样:
MainPlaylistAPI.getMainPlaylist().then(function (data) {
store.dispatch(actions.addMainPlaylist(data));
}, function(e) {
// Handle errors
});
我正在开发一个用 React.js 编写的应用程序,我从 JSON 提要中获取数据,然后我将在应用程序中以各种方式使用这些数据。
我通过 axios 调用提要:
module.exports = {
getMainPlaylist: function () {
var requestUrl = `${MAIN_PLAYLIST_FEED_URL}`;
return axios.get(requestUrl).then(function (res) {
return res.data.playlist
}, function (err) {
alert('error');
});
}
};
在我的 app.jsx 文件中,我有以下内容:
store.subscribe(() => {
var state = store.getState();
console.log('New state: ', state);
});
var mainPlaylist = MainPlaylistAPI.getMainPlaylist();
store.dispatch(actions.addMainPlaylist(mainPlaylist));
在我的动作文件中,我有这个:
export var addMainPlaylist = (mainPlaylist) => {
return {
type: 'ADD_MAIN_PLAYLIST',
mainPlaylist
}
};
在我的减速器文件中我有这个:
export var playlistReducer = (state = [], action) => {
switch (action.type) {
case 'ADD_MAIN_PLAYLIST':
return [
...state,
...action.mainPlaylist
];
default:
return state;
}
};
当我正常使用状态来获取数据时,它工作正常,但我认为因为我正在尝试将商店与 Web 服务一起使用,所以它可能因为异步过程而无法工作。
当我登录到控制台时,我得到这个:
console 1
console 2
我有 .NET 背景,所以我对只在 JavaScript 中工作还很陌生,我不知道从哪里开始解决这个问题。
感谢任何帮助!
我自己设法解决了这个问题。
Axios 是一个基于 promise 的客户端,所以我在调用它的地方使用了 .then()。
所以这个:
var mainPlaylist = MainPlaylistAPI.getMainPlaylist();
store.dispatch(actions.addMainPlaylist(mainPlaylist));
变成这样:
MainPlaylistAPI.getMainPlaylist().then(function (data) {
store.dispatch(actions.addMainPlaylist(data));
}, function(e) {
// Handle errors
});