gpt4 book ai didi

javascript - 调用 setState 后的事件给我以前的状态值

转载 作者:行者123 更新时间:2023-12-01 01:13:35 25 4
gpt4 key购买 nike

我正在尝试为我的 React.js 应用程序创建一个搜索栏。

我已经通过了getSearch() app.js 的子组件导航方法来检索输入值。

getSearch()方法有setState({searchTerm:e.target.value})这是检索到的值,然后我调用 fetchData() setState() 之后的 app.js 方法其中getSearch() .

fetchData()方法this.state.searchTerm作为 fetch() 的主体传递,但是当我输入某些内容并单击 Enter 时,它会给出先前的值 this.state.searchTerm而不是用户输入的最新更新值。

我做错了什么?我正在粘贴我的 app.js 以供审核:

import React, { Component } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";

import "./App.css";

import Navigation from "./components/Navigation";
import Sidebar from "./components/Sidebar";
import Game from "./components/games";
import Profile from "./components/Profile";
import NotFound from "./components/Notfound";

class App extends Component {
constructor(props) {
super(props);
this.state = {
gameFetched: "false",
searchTerm: ""
};
}
getSearch = e => {
if (e.key === "Enter") {
this.setState({
searchTerm: e.target.value
});
this.fetchIGBD()
}
};

componentDidMount() {
this.fetchIGBD();
}

render() {
return (
<div className="App">
<BrowserRouter>
<div>
<Navigation getSearch={this.getSearch} />
<div id="main-wrapper" className="d-flex">
<Sidebar />
<div id="content">
<Switch>
<Route path="/" component={Game} exact />
<Route path="/profile" component={Profile} />
<Route component={NotFound} />
</Switch>
</div>
</div>
</div>
</BrowserRouter>
</div>
);
}

fetchIGBD = () => {
let url = "http://localhost:8080/api-v3.igdb.com/games";
let data ="fields name,cover,first_release_date,genres.name,platforms.name,total_rating;limit 10;sort popularity;where total_rating > 80;where release_dates.platform = 6;";
let search = "search '"+this.state.searchTerm+"';";
if (search !== "") {
data = data + search
console.log(data)
}
fetch(url, {
method: "POST",
body: data,
headers: {
"Content-Type": "application/json",
"user-key": "myid"
}
})
.then(res => res.json())
.then(json => console.log(json))
.catch(error => console.log(error));
this.setState({
gameFetched: "true"
});
};
}

export default App;

最佳答案

您可以使用以下内容:

this.setState({
searchTerm: e.target.value
}, () => {
this.fetchIGBD()
});

setState 函数是异步的,这意味着它不会立即执行。

关于javascript - 调用 setState 后的事件给我以前的状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com