我是 redux 的新手,并尝试使用 Contentful API 获取内容。由于某种原因,我调用的操作没有到达减速器。我附上了我认为相关的代码,任何贡献都将受到高度赞赏。
动作/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
};
}
减速器/index.js
import { combineReducers } from 'redux';
import ContentReducer from './reducer-content';
const rootReducer = combineReducers({
contents: ContentReducer
});
export default rootReducer;
减速器内容.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'));
组件/内容索引.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);