javascript - 为什么不能在另一个方法中更改状态?
问题描述
我创建了一个后端,我可以调用 POST 或 GET 请求来发送/获取列表名称和描述,如下所示。
我的脚本应该像这样工作:
- 页面加载,然后我的应用程序获取列表数据并将其显示在另一个组件中
- 我可以创建一个新列表
- 我的脚本将其发送到后端,成功创建后,我的组件再次获取列表数据并将其显示在同一屏幕上的另一个组件中。
要将数据传递给另一个组件,我想设置状态 (setLists) 以使列表变量可以传递。不幸的是,当
我在函数底部添加.then((data) => setLists(data))
而不是.then((data) => console.log(data))
在getLists()
方法中添加时,我看到未定义。我希望它被更新。console.log(lists)
getLists()
现在我的脚本在一开始就显示了数据,但是使用这条线.then((data) => console.log(data))
让我没有什么可玩的。然后我可以正确保存新数据并预览它作为响应,但我的状态无法像我上面所说的那样更新。
我正在寻找任何解决方案来解决我应该做的事情。
任何代码审查想法将不胜感激。
import React, {useState, useEffect} from "react";
function Form() {
const [lists, setLists] = useState([]);
const [listName, setListName] = useState("");
const [listDescription, setListDescription] = useState("");
useEffect(() => {
getLists()
}, [])
function getLists() {
fetch('http://localhost:5000/lists', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log('error'))
}
function saveList(listName, listDescription) {
fetch('http://localhost:5000/lists', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: listName,
description: listDescription
}),
})
.then((response) => response.json())
.then(data => {console.log(data)})
.catch((error) => console.log('error'))
getLists();
}
function handleSubmit(e) {
e.preventDefault();
saveList(listName, listDescription);
}
return (
<div>
<h1>Form</h1>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="list-name">List name</label>
<input type="text" className="form-control" id="list-name" onChange={e => setListName(e.target.value)} value={listName} placeholder="Enter list name" required />
</div>
<div className="form-group">
<label htmlFor="list-description">List description</label>
<input type="text" className="form-control" id="list-description" onChange={e => setListDescription(e.target.value)} value={listDescription} placeholder="Enter description" required />
</div>
<button type="submit" className="btn btn-success">Save</button>
</form>
</div>
)
}
export default Form;
解决方案
您的解决方案是正确的,您可以这样写getLists
:
.then((data) => setLists(data))
但是如果你写console.log(lists)
在末尾getLists
,那lists
是未定义的很正常。这一行在 promise ( fetch
) 被解决之前执行。
你可以做的就是console.log(lists)
放在return
. 它可能会显示很多时间,但至少您应该看到它lists
已更新。
编辑:我还认为saveList
,您想getLists
在保存列表后调用。所以也许你应该把getLists()
块then
:
fetch('http://localhost:5000/lists', {
method: 'POST',
...
})
.then((response) => response.json())
.then(data => {
console.log(data)
getLists() // <-- here
})
推荐阅读
- javascript - 如何从元素js中获取所有孩子
- ios - UI 测试用例 XCUIElementTypeQueryProvider tableRows 和 tableColumns 计数为 0
- kubernetes - Kubernetes pod 无法解析运行 weave CNI 的集群内的私有 IP 地址
- r - 在 R 中,如何使用行名和列名创建包含在“矩阵”或“数据框”设置中的图?
- php - 全新安装 LEMP 但无法访问网站
- javascript - 如何知道新元素是否添加到 DOM
- javascript - 创建精灵时如何避免重叠?JS-PHASER3
- javascript - 不能有条件地在反应中设置跨度的样式(css模块)
- javascript - 如何为div内的每个元素设置边框颜色?
- c# - 在 Unity3D 中,如何在迭代 FileInfo[] 数组(非阻塞)时异步显示 UI 径向进度条?