我在 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
相同Root Reducer
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
的{{1}}值为:
我错过了什么?如何访问从api调用返回的列表?
由于
答案 0 :(得分:1)
组合缩减器时,可以执行此操作
const rootReducer = combineReducers({
LoginReducer,
PoiReducer
});
表示
const rootReducer = combineReducers({
LoginReducer : LoginReducer,
PoiReducer : LoginReducer
});
这不是你想要的。
应该是
const rootReducer = combineReducers({
loginReducer : LoginReducer,
poiReducer : LoginReducer
});
另外,由于某些原因,你的root reducer里面有一个rootReducer,这有点奇怪。
所以访问poiReducer的方式是
function mapStateToProps(state) {
console.log("State: ", state);
return {
pois: state.rootReducer.poiReducer
};
}