Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么状态不能在另一个方法中更改?_Javascript_Reactjs - Fatal编程技术网

Javascript 为什么状态不能在另一个方法中更改?

Javascript 为什么状态不能在另一个方法中更改?,javascript,reactjs,Javascript,Reactjs,我创建了一个后端,我可以调用POST或获取请求来发送/获取列表名称和描述,如下所示 我的脚本应该像这样工作: 页面加载,然后我的应用程序获取列表数据并将其显示在另一个组件中 我可以创建一个新列表 我的脚本将其发送到后端,成功创建后,我的组件再次获取列表数据,并将其显示在同一屏幕上的另一个组件中 要将数据传递给另一个组件,我需要将状态(setLists)设置为可以传递列表变量。 不幸的是,当我添加 。然后((数据)=>setLists(数据))而不是。然后((数据)=>console.log(数据

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

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

  • 页面加载,然后我的应用程序获取列表数据并将其显示在另一个组件中
  • 我可以创建一个新列表
  • 我的脚本将其发送到后端,成功创建后,我的组件再次获取列表数据,并将其显示在同一屏幕上的另一个组件中
  • 要将数据传递给另一个组件,我需要将状态(setLists)设置为可以传递列表变量。 不幸的是,当我添加
    。然后((数据)=>setLists(数据))
    而不是
    。然后((数据)=>console.log(数据))
    getLists()
    方法中执行
    console.log(lists)
    时,在
    getLists()
    函数的底部我看到未定义。我想更新一下

    现在,我的脚本一开始就显示数据,但使用这一行
    。然后((数据)=>console.log(数据))
    ,这就没有什么可玩的了。然后我可以正确地保存新数据并预览它作为响应,但我的状态不能像上面所说的那样更新

    我正在寻找任何决议,我应该做什么,使它的工作

    任何代码审查想法都将受到赞赏

    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;
    
    import React,{useState,useffect}来自“React”;
    函数形式(){
    const[lists,setLists]=useState([]);
    const[listName,setListName]=useState(“”);
    常量[listDescription,setListDescription]=useState(“”);
    useffect(()=>{
    getLists()
    }, [])
    函数getLists(){
    取('http://localhost:5000/lists', {
    方法:“GET”,
    标题:{
    “内容类型”:“应用程序/json”,
    },
    })
    .then((response)=>response.json())
    .然后((数据)=>console.log(数据))
    .catch((错误)=>console.log('error'))
    }
    函数保存列表(listName、listDescription){
    取('http://localhost:5000/lists', {
    方法:“POST”,
    标题:{
    “内容类型”:“应用程序/json”,
    },
    正文:JSON.stringify({
    名称:listName,
    描述:listDescription
    }),
    })
    .then((response)=>response.json())
    .then(数据=>{console.log(数据)})
    .catch((错误)=>console.log('error'))
    getLists();
    }
    函数handleSubmit(e){
    e、 预防默认值();
    保存列表(listName、listDescription);
    }    
    返回(
    形式
    列表名
    setListName(e.target.value)}value={listName}占位符=“输入列表名”必填项/>
    列表说明
    setListDescription(e.target.value)}value={listDescription}占位符=“输入描述”必填项/>
    拯救
    )
    }
    导出默认表单;
    
    您的解决方案是正确的,您可以在
    getlist
    中编写:

    。然后((数据)=>设置列表(数据))
    
    但是如果您在
    getlist
    的末尾编写
    console.log(lists)
    ,则
    lists
    仍然未定义是正常的。在解析承诺(
    fetch
    )之前执行此行

    您可以做的是将
    console.log(列表)
    放在
    返回之前。它可能会显示很多时间,但至少您应该看到
    列表
    已更新

    编辑:我还认为,在
    保存列表
    中,您希望在保存列表后调用
    getlist
    。因此,也许您应该将
    getlist()
    放在
    然后
    块中:

    fetch('http://localhost:5000/lists', {
    方法:“POST”,
    ...
    })
    .then((response)=>response.json())
    。然后(数据=>{
    console.log(数据)
    
    GetList()//尝试更改
    。然后((数据)=>SetList(数据))
    返回并添加另一个
    useEffect
    hook作为
    useEffect(()=>{console.log('LIST data:',lists);},[lists])
    @emkarachchi不幸的是,您的解析不起作用。我有列表数据:长度:0。返回是什么意思?我的代码中没有返回。@browinski是的:
    返回(…
    谢谢,我明白了。现在的问题是,我的脚本在控制台返回两个位置:1。[]2。我看到的完整数组[]来自useState([])但我不知道为什么