gpt4 book ai didi

javascript - 使用React Redux从异步API调用中获取数据

转载 作者:行者123 更新时间:2023-12-03 06:26:24 25 4
gpt4 key购买 nike

我的 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);
})
}

控制台日志输出:

console.log("POI:", pois)

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相同

根 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.poisundefinedstate 的值来自mapStateToProps是:

state value

我错过了什么?如何访问从 api 调用返回的列表?

谢谢

最佳答案

当你组合你的 reducer 时,你会这样做

const rootReducer = combineReducers({
LoginReducer,
PoiReducer
});

这意味着

const rootReducer = combineReducers({
LoginReducer : LoginReducer,
PoiReducer : LoginReducer
});

这不是你想要的。

应该是

const rootReducer = combineReducers({
loginReducer : LoginReducer,
poiReducer : LoginReducer
});

此外,由于某种原因,你的根 reducer 内部有一个 rootReducer,这有点奇怪。

所以访问poiReducer的方式是

function mapStateToProps(state) {
console.log("State: ", state);
return {
pois: state.rootReducer.poiReducer
};
}

关于javascript - 使用React Redux从异步API调用中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38632959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com