我是reactjs/redux的初学者,找不到如何在redux应用程序中使用api调用来检索数据的简单使用示例。我猜您可以使用jquery ajax调用,但可能还有更好的选择?
发布于 2016-10-03 04:09:02
JSfiddle;http://jsfiddle.net/cdagli/b2uq8704/6/
它使用redux、redux-thunk和fetch。
获取方法;
function fetchPostsWithRedux() {
return (dispatch) => {
dispatch(fetchPostsRequest());
return fetchPosts().then(([response, json]) =>{
if(response.status === 200){
dispatch(fetchPostsSuccess(json))
}
else{
dispatch(fetchPostsError())
}
})
}
}
function fetchPosts() {
const URL = "https://jsonplaceholder.typicode.com/posts";
return fetch(URL, { method: 'GET'})
.then( response => Promise.all([response, response.json()]));
}上面使用的操作:
(注意:您可以定义许多操作,例如,可以使用fetchPostRequest来显示加载指示器。或者,您可以在不同HTTP状态代码的情况下分派不同的操作。)
function fetchPostsRequest(){
return {
type: "FETCH_REQUEST"
}
}
function fetchPostsSuccess(payload) {
return {
type: "FETCH_SUCCESS",
payload
}
}
function fetchPostsError() {
return {
type: "FETCH_ERROR"
}
}在你的reducer中,你可以将post加载到state;
const reducer = (state = {}, action) => {
switch (action.type) {
case "FETCH_REQUEST":
return state;
case "FETCH_SUCCESS":
return {...state, posts: action.payload};
default:
return state;
}
} 通过连接后,您可以访问组件中的状态和操作;
connect(mapStateToProps, {fetchPostsWithRedux})(App);发布于 2016-10-02 13:15:34
创建一个操作,您可以在其中执行对API的请求。您可以使用诸如axios或fetch这样的库,这些库返回一个promise。
操作/index.js:
import axios from 'axios';
export const FETCH_SOMETHING= 'FETCH_SOMETHING;
const ROOT_URL = 'http://api.youapi.com';
export function fetchWeather(city) {
const url = `${ROOT_URL}&q=${aParamYouMayNeed}`;
const request = axios.get(url);
return {
type: FETCH_SOMETHING,
payload: request
};
}然后在reducer中,在解析后使用promise结果,如下所示:
reducers/reducer_omething.js:
import { FETCH_SOMETHING} from '../actions/index';
export default function(state = [], action) {
switch (action.type) {
case FETCH_SOMETHING:
return [ action.payload.data, ...state ];
}
return state;
}从斯蒂芬·格里德那里借来的代码。这是他的回购:https://github.com/StephenGrider/ReduxCasts/tree/master/weather/src
https://stackoverflow.com/questions/39813984
复制相似问题