【问题标题】:How to get a resolved promise to my component with Redux Promise?如何使用 Redux Promise 为我的组件获得已解决的承诺?
【发布时间】:2016-10-04 22:19:09
【问题描述】:

我正在我的操作中发出请求 - 从需要将一些数据加载到我的组件中的 API 中提取。我让它在组件挂载时启动该请求,但我似乎无法让 Redux-Promise 正常工作,因为它只是不断返回:

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}

当我尝试在我的开发工具中控制台记录我的 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);

非常感谢任何和所有帮助。谢谢你。

【问题讨论】:

    标签: reactjs redux redux-promise


    【解决方案1】:

    Redux-promise 返回一个正确的 Promise 对象,因此您可以稍微更改代码以避免立即执行。

    class Home extends Component {
      componentWillMount() {
        this.props.fetchReviews().then((whatever) => { console.log('resolved')})
      }
      // ...
    }
    

    【讨论】:

    • 谢谢 - 是的,这很有帮助。正如您所指出的,Console.logging 立即执行它,它会在运行后立即执行,因此是未决承诺的原因。我在发布此内容后安装了 redux-logger,并且能够看到 promise 在它到达我的商店时解决。
    猜你喜欢
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 2021-02-02
    • 2018-04-02
    • 2023-03-24
    • 1970-01-01
    • 2014-09-25
    • 2020-11-02
    相关资源
    最近更新 更多