Reactjs 如何使用redux执行api调用?
我最近在学习react redux。现在,我有点困惑于如何执行Reactjs 如何使用redux执行api调用?,reactjs,typescript,react-redux,Reactjs,Typescript,React Redux,我最近在学习react redux。现在,我有点困惑于如何执行api调用 这是我的行动 export const fetchEvent = () => async ( dispatch: Dispatch ) => { dispatch({ type: ActionTypes.FETCH_EVENT_REQUEST }); try { const response = await axios.get<EvenData[]>(
api调用
这是我的行动
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 });
}
};
export const fetchEvent=()=>async(
派遣:派遣
) => {
分派({type:ActionTypes.FETCH_EVENT_REQUEST});
试一试{
const response=等待axios.get(
`https://jsonplaceholder.typicode.com/todos/`
);
派遣({
类型:ActionTypes.FETCH\u事件\u成功,
有效载荷:response.data
});
}捕获(错误){
分派({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);
const-mapStateToProps=(状态:ActionTypes)=>({});
const dispatchProps={};
类型道具=返回类型和调度道具类型;
类型State={};
类EventList扩展了React.Component{
componentDidMount(){
//调度(fetchEvent());
}
render(){
返回(
{}
);
}
}
导出默认连接(
MapStateTops,
派遣道具
)(事件列表);
那么我如何进行api调用呢?在my
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);
import{fetchEvent}from'action.ts'//更改为正确的路径
常量mapStateToProps=(状态:ActionTypes)=>({});
const mapDispatchToProps=(调度:调度)=>{
返回{
fetchEvent:()=>{
分派(fetchEvent())
}
};
};
类型道具=返回类型和返回类型;
类型State={};
类EventList扩展了React.Component{
componentDidMount(){
this.props.fetchEvent()
}
render(){
返回(
{}
);
}
}
导出默认连接(
MapStateTops,
mapDispatchToProps
)(事件列表);
看看这一点。但我建议尝试使用功能组件和redux挂钩,这样更容易,更容易理解。除了SebMaz93答案,我建议使用,而不是自己实现。你可以用很多钩子。