我在我的操作中发出请求 - 从需要将某些数据加载到我的组件中的API中提取。我在组件安装时启动了该请求,但我似乎无法使Redux-Promise正常工作,因为它只是不断返回:
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
在我的开发工具中,当我尝试console.log时,我的componentWillMount方法中的值。
以下是我的代码:
商店&路由器
import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import promiseMiddleware from 'redux-promise';
import { Provider } from 'react-redux';
import { Router, hashHistory } from 'react-router';
import routes from './routes';
import rootReducer from './reducers';
const store = createStore(
rootReducer,
applyMiddleware(promiseMiddleware)
);
render(
<Provider store={store}>
<Router history={hashHistory} routes={routes} />
</Provider>,
document.getElementById('root')
);
动作
import axios from 'axios';
export const FETCH_REVIEWS = 'FETCH_REVIEWS';
export const REQUEST_URL = 'http://www.example.com/api';
export function fetchReviews() {
const request = axios.get(REQUEST_URL);
return {
type: FETCH_REVIEWS,
payload: request
};
};
评论减速器
import { FETCH_REVIEWS } from '../actions/reviewActions';
const INITIAL_STATE = {
all: []
};
export default function reviewsReducer(state = INITIAL_STATE, action) {
switch(action.type) {
case FETCH_REVIEWS:
return {
...state,
all: action.payload.data
}
default:
return state;
}
}
Root Reducer
import { combineReducers } from 'redux';
import reviewsReducer from './reviewsReducer';
const rootReducer = combineReducers({
reviews: reviewsReducer
});
export default rootReducer;
组件
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchReviews } from '../../actions/reviewActions';
class Home extends Component {
componentWillMount() {
console.log(this.props.fetchReviews());
}
render() {
return (
<div>List of Reviews will appear below:</div>
);
}
}
export default connect(null, { fetchReviews })(Home);
非常感谢任何和所有帮助。谢谢。
答案 0 :(得分:2)
Redux-promise返回一个正确的Promise对象,因此您可以稍微更改一下代码以避免立即执行。
class Home extends Component {
componentWillMount() {
this.props.fetchReviews().then((whatever) => { console.log('resolved')})
}
// ...
}