动作不会触发Redux中的reducer

时间:2018-08-10 14:55:18

标签: reactjs redux redux-promise

我是Redux的新手,正在尝试使用Contentful API来获取内容。由于某种原因,我调用的动作无法到达减速器。我已附上我认为相关的代码,我们将不胜感激。

actions / index.js

import axios from 'axios';

const API_BASE_URL = 'https://cdn.contentful.com';
const API_SPACE_ID = 'xxxxxxxxxxxxx';
const API_KEY ='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

const FETCH_CONTENT = 'fetch_content';

export function fetchContent() {
  const request = axios.get(`${API_BASE_URL}/spaces/${API_SPACE_ID}/environments/master/entries?access_token=${API_KEY}`);
  return {
    type: FETCH_CONTENT,
    payload: request
  };
  }

reducers / index.js

import { combineReducers } from 'redux';
import ContentReducer from './reducer-content';

const rootReducer = combineReducers({
  contents: ContentReducer
});

export default rootReducer;

reducer-content.js

import {FETCH_CONTENT} from '../actions';
const INITIAL_STATE = { all: [] };

export default function(state = INITIAL_STATE, action){
  switch(action.type){
    case FETCH_CONTENT:
      return { ...state, all: action.payload.data.items };

  default:
  return state;
  }
}

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route, Switch } from "react-router-dom";
import promise from 'redux-promise';
import { logger } from 'redux-logger'


import ContentIndex from './components/content-index';
import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware(promise, logger)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <BrowserRouter>
      <div>
      <Route  path = "/" component = {ContentIndex}/>
    </div>
    </BrowserRouter>

  </Provider>
  , document.querySelector('.container'));

components / content-index.js

import React, {Component} from 'react';
import {fetchContent} from '../actions';
import {connect} from 'react-redux';
import _ from 'lodash';

class ContentIndex extends Component {
  componentDidMount(){
    this.props.fetchContent();
  }

  renderContent(props){
    return this.props.contents.map((content, index) => {
      return (
        <article key={content.sys.id}>
          <h3>{content.fields.name}</h3>
          <p>{content.fields.website}</p>
        </article>
      );
    });
  }

  render(){
    return(
      <div>
      <h3>Content</h3>
      {this.renderContent()}
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {contents: state.contents.all};
}
// export default CharacterIndex;
export default connect(mapStateToProps, {fetchContent})(ContentIndex);

3 个答案:

答案 0 :(得分:1)

更新

似乎我在这里错了(感谢@Dave Newton的评论)。 redux-promise等待一个诺言,如果收到一个诺言,则将其解析并分派值。因此,在这里使用异步功能和使用动作创建器是没有用的。


您正在使用redux-promise,我不知道它如何处理这种情况,但是在它的Github存储库中有一个带有redux-actions的示例,它使用了一个异步函数。我对redux-thunk较为熟悉,但是在这里使用异步操作创建者可能很适合您的情况。

尝试一下:

export async function fetchContent() {
  const request = await axios.get(`${API_BASE_URL}/spaces/${API_SPACE_ID}/environments/master/entries?access_token=${API_KEY}`);
  return {
    type: FETCH_CONTENT,
    payload: request
  };
}

答案 1 :(得分:0)

axios.get()返回promise。

所以您需要使用async / await。

答案 2 :(得分:0)

您可以通过执行以下操作来简化代码,避免调度异步操作以及使用Redux中间件:

  • fetchContent()转换为异步函数,该函数将返回带有有效内容中各项的操作
  • 创建一个mapDispatchToProps,它创建一个函数来调度fetchContent()返回的动作

fetchContent()看起来像这样:

export async function fetchContent() {
  const request = await axios.get(`${API_BASE_URL}/spaces/${API_SPACE_ID}/environments/master/entries?access_token=${API_KEY}`);
  return {
    type: FETCH_CONTENT,
    payload: request.data.items
  };
}

connect看起来像这样:

const mapStateToProps = (state) => {
  return {contents: state.contents.all};
}

const mapDispatchToProps = (dispatch) => {
  return {
    loadItems: () => fetchContent().then(action => dispatch(action))
  }
}

// export default CharacterIndex;
export default connect(mapStateToProps, mapDispatchToProps)(ContentIndex);

您的减速器看起来像这样:

export default function(state = INITIAL_STATE, action){
  switch(action.type){
    case FETCH_CONTENT:
      return { ...state, all: action.payload };

  default:
  return state;
  }
}

componentDidMount()看起来像这样:

  componentDidMount(){
    this.props.loadItems();
  }