在redux action中调用两个API,其中一个API调用依赖于另一个API的返回内容,可以通过以下步骤实现:
fetchData1
,另一个叫做fetchData2
。fetchData1
中,首先发起第一个API的请求,并在请求成功后,将返回的数据作为参数传递给fetchData2
。export const fetchData1 = () => {
return async (dispatch) => {
try {
const response = await fetch('API1_URL');
const data = await response.json();
// 调用fetchData2,并将API1的返回数据作为参数传递
dispatch(fetchData2(data));
} catch (error) {
// 处理错误
}
};
};
fetchData2
中,接收API1的返回数据作为参数,并发起第二个API的请求。export const fetchData2 = (data1) => {
return async (dispatch) => {
try {
// 根据API1的返回数据,构造第二个API的请求参数
const params = {
data1,
};
const response = await fetch('API2_URL', {
method: 'POST',
body: JSON.stringify(params),
});
const data = await response.json();
// 处理第二个API的返回数据
dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data });
} catch (error) {
// 处理错误
}
};
};
fetchData1
来触发整个流程。import { connect } from 'react-redux';
import { fetchData1 } from 'actions';
class MyComponent extends React.Component {
componentDidMount() {
this.props.fetchData1();
}
// ...
}
export default connect(null, { fetchData1 })(MyComponent);
这样,当组件挂载时,fetchData1
会被调用,然后依次调用两个API,并将第一个API的返回数据传递给第二个API。最终,第二个API的返回数据会被存储到redux store中,可以在组件中通过props获取并使用。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云