React-Redux-操作返回未定义

时间:2019-04-02 12:46:27

标签: reactjs react-redux

我正在尝试通过操作进行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));
        });
};

}

PAGE:

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);

1 个答案:

答案 0 :(得分:0)

首先,我恳请您检查呼叫是否已使用Postman或类似工具正常工作。

第二,我认为您对如何使用React和Redux管理数据有些误解。

您要获取的数据必须存储在redux存储中,当您调用该操作创建者时,应将响应中接收到的数据分派给reducer。 该化简器将存储该信息,然后将使您的组件再次呈现,并且所提取的数据将在组件道具上可用。

此处有更多信息:Redux data flow