[英]Fetching data from async api call using react redux
我在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
,而mapStateToProps
的state
的值是:
我想念什么? 如何訪問從api調用返回的列表?
謝謝
當您結合使用減速器時,您會這樣做
const rootReducer = combineReducers({
LoginReducer,
PoiReducer
});
意思是
const rootReducer = combineReducers({
LoginReducer : LoginReducer,
PoiReducer : LoginReducer
});
那不是您想要的。
它應該是
const rootReducer = combineReducers({
loginReducer : LoginReducer,
poiReducer : LoginReducer
});
另外,由於某種原因,您在根減速器中有一個rootReducer,這有點奇怪。
所以訪問poiReducer的方法是
function mapStateToProps(state) {
console.log("State: ", state);
return {
pois: state.rootReducer.poiReducer
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.