[英]Why state cannot be changed inside another method?
我创建了一个后端,我可以调用 POST 或 GET 请求来发送/获取列表名称和描述,如下所示。
我的脚本应该像这样工作:
要将数据传递给另一个组件,我想将 state (setLists) 设置为可以传递列表变量。 不幸的是,当我在getLists()
方法中添加.then((data) => setLists(data))
而不是 .then( .then((data) => console.log(data))
时,我在执行console.log(lists)
getLists()
function 的底部我看到未定义。 我希望它被更新。
现在我的脚本在一开始就显示数据,但是使用这一行.then((data) => console.log(data))
让我没有什么可玩的。 然后我可以正确保存新数据并预览它作为响应,但是我的 state 无法更新,正如我上面所说的。
我正在寻找任何解决方案来解决我应该做的事情。
任何代码审查想法将不胜感激。
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))
但是如果你在getLists
的末尾写console.log(lists)
,那么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
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.