[英]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.