首页 > 解决方案 > 为什么不能在另一个方法中更改状态?

问题描述

我创建了一个后端,我可以调用 POST 或 GET 请求来发送/获取列表名称和描述,如下所示。

我的脚本应该像这样工作:

  1. 页面加载,然后我的应用程序获取列表数据并将其显示在另一个组件中
  2. 我可以创建一个新列表
  3. 我的脚本将其发送到后端,成功创建后,我的组件再次获取列表数据并将其显示在同一屏幕上的另一个组件中。

要将数据传递给另一个组件,我想设置状态 (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;

标签: javascriptreactjs

解决方案


您的解决方案是正确的,您可以这样写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
  })

推荐阅读