我正在尝试通过操作进行API调用。我正在使用onchange事件来进行呼叫并添加ID。
我创建了MapDispatchToProps,我通过bindActionCreators绑定了我的动作。当我调用该动作时,我发现他正在进行API调用并获得正确的值。只有当它返回到onchange事件时才会被定义。
我尝试了几个示例和复数教程,但这些都不起作用。
行动:
export function loadStanding(id) {
var url = "http://api.football-data.org/v2/competitions/" + id + "/standings";
return function (dispatch) {
return fetch(url,
{
mode: "cors"
})
.then(
response => response.json(),
error => console.log('An error occurred.', error)
)
.then((json) => {
console.log("=== LOADSTANDING ACTION ===");
console.log(json);
dispatch(loadStandingsSucces(json));
});
};
}
页:
class HomePage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = { standings: [], selectedId: 0 };
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
event.preventDefault();
this.props.actions.loadStanding(event.target.value).then(function(output) {
console.log("=== HANDLECHANGE ===");
console.log(output);
});
}
render() {
const { competitions = [] } = this.props.competitions;
const compIds = [2000,2001,2002,2003,2013,2014,2015,2016,2017,2018,2019,2021];
return (
<div className="flex-container">
<div className="row">
<div className="flex-item">
<h2>Kies een competitie:</h2>
</div>
<div className="flex-item">
<DropdownComponent onChange={this.handleChange} value="id" itemKey="id" text="name" competitions={competitions.filter(function(comp) { return compIds.includes(comp.id); })} />
</div>
<div className="flex-item">
{/* <TableComponent /> */}
</div>
</div>
</div>
);
}
}
HomePage.propTypes = {
competitions: PropTypes.any.isRequired,
actions: PropTypes.object.isRequired
};
function mapStateToProps(state) {
return {
competitions: state.competitions,
standings: state.standings
};
}
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators(standingActions, dispatch)
};
};
export default connect(mapStateToProps, mapDispatchToProps)(HomePage);
首先,我建议您使用Postman或类似工具检查呼叫是否正常。
第二,我认为你对如何使用React和Redux管理数据有一点误解。
您正在获取的数据必须存储在redux存储中,当您调用该操作创建者时,响应中收到的数据应该被分派到reducer。该reducer将存储该信息,然后将导致您的组件再次渲染,并且所获取的数据将在组件props上可用。
更多信息:Redux data flow