gpt4 book ai didi

reactjs - 如何使用redux执行api调用?

转载 作者:行者123 更新时间:2023-12-04 07:35:34 24 4
gpt4 key购买 nike

我最近在学习 react-redux。现在我有点困惑如何执行 api call .
这是我的 action.ts

export const fetchEvent = () => async (
dispatch: Dispatch
) => {
dispatch({ type: ActionTypes.FETCH_EVENT_REQUEST });

try {
const response = await axios.get<EvenData[]>(
`https://jsonplaceholder.typicode.com/todos/`
);
dispatch<FetchEventAction>({
type: ActionTypes.FETCH_EVENT_SUCCESS,
payload: response.data
});

} catch (error) {
dispatch({ type: ActionTypes.FETCH_EVENT_FAILURE, error });
}
};
这是我的事件列表,这是我要调用 api 调用的地方
const mapStateToProps = (state: ActionTypes) => ({});
const dispatchProps = {};

type Props = ReturnType<typeof mapStateToProps> & typeof dispatchProps;

type State = {};

class EventList extends React.Component<Props, State> {
componentDidMount() {
// dispatch(fetchEvent());
}

render() {
return (
<section>
<p>{ }</p>
</section>
);

}
}

export default connect(
mapStateToProps,
dispatchProps
)(EventList);
那么我怎样才能进行 api 调用呢?在我的 componentDidMount 里面

最佳答案

您缺少 mapDispatchToProps ,您使用的那个是空的 {}。

import {fetchEvent} from 'action.ts' // change to correct path

const mapStateToProps = (state: ActionTypes) => ({});
const mapDispatchToProps = (dispatch: Dispatch) => {
return {
fetchEvent: () => {
dispatch(fetchEvent())
}
};
};

type Props = ReturnType<typeof mapStateToProps> & ReturnType<typeof mapDispatchToProps>;

type State = {};

class EventList extends React.Component<Props, State> {
componentDidMount() {
this.props.fetchEvent()
}

render() {
return (
<section>
<p>{ }</p>
</section>
);

}
}

export default connect(
mapStateToProps,
mapDispatchToProps
)(EventList);

关于reactjs - 如何使用redux执行api调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67759441/

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