0
我遇到了在我的React Redux項目中發生的api調用問題。這是項目的代碼片段。使用react redux從異步API調用獲取數據
poiAction.js
export function poiSuccess(pois) {
// The log detail is below
console.log("POI: ", pois);
return {
pois,
type: POI_FETCH_SUCCESS
};
}
export function poiFetch(pois) {
return {
pois,
type: POI_FETCH_ATTEMPT
};
}
export function fetchPoi(token) {
return dispatch =>
axios({
method: 'get',
url: 'http://localhost:9090/poi',
headers: {
'x-access-token': token
},
})
.then((pois) =>{
// let poi = pois.data[0];
// console.log("POIS: ", pois.data[0]);
dispatch(poiSuccess(pois));
})
.catch((error) => {
throw(error);
})
}
控制檯日誌輸出:
poiReducer.js
export default function poi(state = [], action){
switch(action.type){
case POI_FETCH_ATTEMPT:
return state;
case POI_FETCH_FAILED:
return state;
case POI_FETCH_SUCCESS:
// The console log output is same as poiAction
console.log("Reducer: ", action.pois);
return [action.pois, ...state];
break;
default:
return state;
}
}
控制檯日誌輸出是相同poiAction
根異徑
const rootReducer = combineReducers({
LoginReducer,
PoiReducer
});
顯示從API調用列表中的成分:
Dashboard.js
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
poi: '',
token: null
};
}
componentWillMount() {
let token = sessionStorage.getItem("token");
this.setState({token});
this.props.actions.fetchPoi(token);
}
render() {
console.log("POIS: ", this.props.pois);
return (
<div>
<h1>Dashboard</h1>
</div>
);
}
}
Dashboard.propTypes = {
pois: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired,
};
function mapStateToProps(state) {
console.log("State: ", state);
return {
pois: state.poiReducer
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(poiAction, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);
這裏this.props.pois
是undefined
和state
從mapStateToProps
值:
我缺少什麼?我如何訪問從api調用返回的列表?
感謝
至於我,你必須返回 - >'功能(調度){axios.get(),然後(//派遣)}',而不是'return dispatch()...'。請看看[this](https://github.com/oviava/react-redux-axios-example/blob/master/src/actions/actions.js)example –
@TheReason我正在使用'thunk'和'redux-promise'作爲中間件。 –