如何在另一个代码已经结束运行后运行代码?



在不到 1 秒的时间内,我必须将某些内容发布到 JSON 文件中,然后更新确切的数据。运行代码时,似乎我将数据发布在 JSON 文件中,但当我尝试获取它时,它会获取旧数据,而不是更新的数据。

发布方法结束运行后如何运行 get 方法?

我运行了这个帖子方法

import Game from "./components/Game/Game";
class App extends React.Component {  
postUserInfo(){
fetch("http://localhost:8080/api/users" , {
method: "post" ,
mode: "cors",
headers: {
"Content-type": "application/json",
},
body:JSON.stringify({username:this.state.userInput, bestscore:0})
})
.then((res) => res.json())
.then((data => {console.log(data)}))
.catch((error) => {
console.log(error);
});
} 
}   

然后在另一个类中,我在 post 方法之后立即运行此 get 方法

class Game extends React.Component {
getUserInfo() {
fetch("http://localhost:8080/api/users" , {mode: "cors"})
.then((res) => res.json())
.then((data => {
this.setState({ usersInfoArray: data})
var _userid = data[data.length-1].id;
var _username = data[data.length-1].username;
var _bestscore = data[data.length-1].bestscore;
this.setState({ userid: _userid, username: _username, bestscore: _bestscore});
}))
} 
}
componentDidMount(){
this.getUserInfo();
this.render();
}

我想你可以在另一个组件中调用postUserInfo((,然后移动到新的组件 然后在组件挂载后,调用 getUserInfo((

我说的对吗?

您导航到(或创建(其他组件逻辑必须在 postUserInfo(( 中 近

.then((data => {console.log(data)}))

执行此操作的最简单方法可能是在 App 的状态中维护一个dataPosted标志,并将该标志传递给Game组件。如果dataPosted标志为 true,则加载数据。

应用.jsx

import Game from "./components/Game/Game";
class App extends React.Component {  
constructor() {
super();
this.state = { dataPosted: false }
}
postUserInfo(){
fetch("http://localhost:8080/api/users" , {
method: "post" ,
mode: "cors",
headers: {
"Content-type": "application/json",
},
body:JSON.stringify({username:this.state.userInput, bestscore:0})
})
.then((res) => res.json())
.then(data => {
this.setState({ dataPosted: true })
})
.catch((error) => {
console.log(error);
});
} 
}   
render() {
<Game dataPosted={this.state.dataPosted} />
}
}

游戏.jsx

class Game extends React.Component {
componentDidUpdate() {
if (this.props.dataPosted) {
this.getUserInfo();
}
}
getUserInfo() {
fetch("http://localhost:8080/api/users" , {mode: "cors"})
.then((res) => res.json())
.then((data => {
this.setState({ usersInfoArray: data})
var _userid = data[data.length-1].id;
var _username = data[data.length-1].username;
var _bestscore = data[data.length-1].bestscore;
this.setState({ userid: _userid, username: _username, bestscore: _bestscore});
}))
} 
}

相关内容

最新更新