ReactJS - 在fetch()完成之前运行的显式代码

时间:2018-05-11 22:32:15

标签: javascript reactjs fetch

我的应用的一些背景知识:

  • 后端 - Python,Flask。该数据库目前只是嵌套的词典和列表
  • 前端 - Reactjs

我将参考的功能:

  • FetchPlayers() - 使用fetch()从后端获取包含其中所有玩家的数组。它还使用setState()将玩家添加到州。
  • EditPlayer(playerid) - 使用fetch()POST请求后端更改其中一个播放器的信息。

因此,当用户启动页面时,会调用FetchPlayers()来获取将要显示的玩家列表。用户还可以通过菜单编辑这些玩家信息。当用户确认编辑时(通过按下按钮),首先应用程序调用EditPlayer(),然后在调用FetchPlayers()之后的行中,更新网页上的播放器列表。

问题是页面没有使用新编辑进行更新。对我来说,我必须重新加载页面的新编辑视图。这表明在EditPlayer()之前以某种方式调用了FetchPlayers()。有谁知道我怎么解决这个问题?

提前致谢!

修改

edit_player(_playerid, _newfirstname, _newlastname, _newclass) {
    fetch('http://' + Globals.BaseIP + Globals.PortForBackend + '/api/editplayer', {
        //Options for the fetch request
        method:'POST',
        headers: {
            //Header objects
            'Accept':'application/json, text/plain, */*',
            'Content-type':'application/json'
        },
        body:JSON.stringify({UserID:UserServiceLocal.UserID(), token:UserServiceLocal.token(), GameID:this.props.gameID, PlayerID:_playerid, Firstname:_newfirstname, Lastname:_newlastname, Class:_newclass}),
        mode:'cors'
    })
    .catch((error) => console.log(error));


}

FetchPlayers的代码

FetchPlayers () {
    fetch('http://' + Globals.BaseIP + Globals.PortForBackend + '/api/fetchplayers', {
        //Options for the fetch request
        method:'POST',
        headers: {
            //Header objects
            'Accept':'application/json, text/plain, */*',
            'Content-type':'application/json'
        },
        body:JSON.stringify({UserID:UserServiceLocal.UserID(), token:UserServiceLocal.token(), GameID:this.props.gameID}),
        mode:'cors'
    })
    .then((res) => res.json())
    .then((data) => this.parse_fetch_players_response(data))
    .catch((error) => console.log(error))
}


parse_fetch_players_response(data) {
    console.log(data['players']);
    this.setState({Playerlist:data['players']});
    this.ListScrollToBottom();
}

确认编辑时运行的代码

Btn_EditPlayer() {
    this.edit_player(this.state.playereditID, this.state.playereditName, 
    this.state.playereditLastname, this.state.playereditClass);
    this.FetchPlayers();

渲染功能:

return (
                <div className="PageFooter" onKeyPress={(event) => this.EnterKeyPress_EditPlayer(event)}>
                    <Textinput className="FirstNameTextbox" id="playereditName" label="First name" value={this.state.playereditName} onChange={this.textinput_handleChange}/>
                    <Textinput className="LastNameTextbox" id="playereditLastname" label="Last name" value={this.state.playereditLastname} onChange={this.textinput_handleChange}/>
                    <Textinput className="ClassTextbox" id="playereditClass" label="Class" value={this.state.playereditClass} onChange={this.textinput_handleChange}/>
                    <button id='editPlayerButton' className="mdc-button mdc-button--unelevated mdl-button--colored mdc-ripple-surface" onClick={() => this.Btn_EditPlayer()}>Edit Player</button>
                    <button id="cancel-edit-player-btn" className="mdc-button mdc-button--raised mdl-button--colored mdc-ripple-surface" onClick={() => this.EditPlayer_Cancel_Btn()}>Cancel</button>
                </div>
            );

列表元素渲染功能:

return (
            <div>
                <ul className="mdc-list" id="list-container" >

                    <li role="separator" className="mdc-list-divider"></li>

                    <li className="mdc-list-item" >
                        <span className="mdc-list-item__text list_text_firstname">
                            <b>Firstname</b>
                        </span>

                        <span className="mdc-list-item__text list_text_lastname">
                            <b>Lastname</b>
                        </span>

                        <span className="mdc-list-item__text list_text_class">
                            <b>Class</b>
                        </span>

                        <span className="mdc-list-item__graphic" role="presentation">
                            <i className="material-icons list_edit_icon">edit</i>
                            <i className="material-icons list_remove_icon">delete</i>

                        </span>
                    </li>
                    <li role="separator" className="mdc-list-divider"></li>

                    <ListEntry ListItemCSS="selected-list-entry" firstname="This is above" lastname="Butter" class="Jelly" id="1" delete_self={(playerID) => this.delete_item(playerID)} edit_button_clicked={(playerID) => this.Edit_Button_Clicked(playerID)}/>
                    <ListEntry firstname="Peanut" lastname="Butter" class="Jelly" id="1" delete_self={(playerID) => this.delete_item(playerID)} edit_button_clicked={(playerID) => this.Edit_Button_Clicked(playerID)}/>




                        {playerListItems}


                    </ul>
            </div>

            );

3 个答案:

答案 0 :(得分:1)

尝试从this.FetchPlayers()移除Btn_EditPlayer()并将其添加为edit_player的回调,如下所示:

this.edit_player(this.state.playereditID, this.state.playereditName, 
    this.state.playereditLastname, this.state.playereditClass, this.FetchPlayers);

edit_player(_playerid, _newfirstname, _newlastname, _newclass, callBack) {
    fetch('http://' + Globals.BaseIP + Globals.PortForBackend + '/api/editplayer', {
        //Options for the fetch request
        method:'POST',
        headers: {
            //Header objects
            'Accept':'application/json, text/plain, */*',
            'Content-type':'application/json'
        },
        body:JSON.stringify({UserID:UserServiceLocal.UserID(), token:UserServiceLocal.token(), GameID:this.props.gameID, PlayerID:_playerid, Firstname:_newfirstname, Lastname:_newlastname, Class:_newclass}),
        mode:'cors'
    }).then((res) => {
        // run your callback (fetchPlayers in this case) only when we know the update is done.
       callBack()
    }).catch((error) => console.log(error));
}

编辑(拼写错误)

答案 1 :(得分:0)

没有看到代码就不可能知道,但通常问题是你没有将信息存储在状态中,或者你的JSX在渲染返回中没有使用 this.state 的属性所以它不知道要重新渲染。

答案 2 :(得分:0)

在完成更新数据之前,您的后端可能会向您发送获取请求。

不是从确认代码中调用FetchPlayers(),为什么不直接更新状态?

Btn_EditPlayer() {
    this.edit_player(this.state.playereditID, this.state.playereditName, 
    this.state.playereditLastname, this.state.playereditClass);
    this.setState({
    //your parameters here
    });