我希望将数据从一个API get请求传递给另一个。我想传递的属性是我的API返回的第一个属性的ID。使用此属性,我想将ID注入第二个API调用以专门调用对象。此端点将返回ClickUrl。我想返回此URL并将其注入我视图中的链接href。
下面是我的视图,其中我映射了一个包含我的第一个api调用的数组。我想将promo.merch_id传递回第二个api调用并返回ClickUrl的值。
class AZFeatStores extends Component {
componentWillMount() {
this.props.fetchPromo();
}
constructor(props) {
super(props);
}
getPromoLink(merchantID) {
this.props.fetchPromoClick(merchantID);
}
renderMerchPromo() {
if(!this.props.promos) {
return <div>Loading... </div>;
}
else {
return this.props.promos.map((promo) => {
return (
<div className="feat-inner col-md-3" key={promo.promotion_id}>
<div className="merch-img">
<img src={promo.image_125} alt="merch-img"/>
</div>
<span className="cash-back">{promo.final_rebate} Cash Back </span>
<Link to="This is where I want to inject the URL" className="shop-now">Shop Now</Link>
<a href="#" className="learn-more">Learn More</a>
</div>
);
});
}
}
render() {
return(
<div className="col col-md-12">
{ this.renderMerchPromo() }
</div>
);
}
}
function mapStateToProps(state) {
return { promos: state.promos.all};
}
export default connect( mapStateToProps, { fetchPromo })( AZFeatStores );
我的动作创作者
export function fetchPromo() {
const request = axios.get(`${ROOT_URL}/promos/${PROMO_ID}/ptypes/${PTYPE}`, {
headers: headers
});
return {
type: FETCH_PROMOS,
payload: request
};
}
export function fetchPromoClick(merchantID) {
const request = axios.get(`${ROOT_URL}/getclick/${merchantID}`, {
headers: headers
});
return {
type: FETCH_PROMO_LINK,
payload: request
};
}
我的减速机
import { FETCH_PROMOS, FETCH_PROMO_LINK } from '../actions/promotions';
const INITIAL_STATE = { all: [] ,promo: null };
export default function ( state = INITIAL_STATE, action ) {
switch (action.type) {
case FETCH_PROMOS:
return { ...state, all: action.payload.data.method_response.promos.merch.partner };
case FETCH_PROMO_LINK:
return { ...state, links: action.payload.data.method_response };
default:
return state;
}
}
我是新手,所以不要讨厌我的代码:)
答案 0 :(得分:0)
您可以等到第一个API调用的承诺得到解决,然后使用先前API调用的响应调用第二个API。最后返回第二次调用的承诺,就像这样。您只需要在此处链接API调用,因为它们彼此依赖。
export function fetchPromo() {
const request = axios.get(`${ROOT_URL}/promos/${PROMO_ID}/ptypes/${PTYPE}`, {
headers: headers
}).then(response => {
// Extract your ID value here.
// Then call the second endpoint with that ID value.
return axios.get('/user?ID={response.id}'); // using response.data
});
return {
type: FETCH_PROMOS,
payload: request
};
}
希望这会有所帮助。快乐的编码!