【问题标题】:React dev tools show data state, console shows emptyReact 开发工具显示数据状态,控制台显示为空
【发布时间】:2020-11-07 19:37:23
【问题描述】:

我在我的 React 应用程序中遇到了一个奇怪的状态问题。在此我使用一种状态和一种 useEffect。状态用于存储从 jsonplaceholder 获取的帖子。获取并设置写入在 useffect 中的状态,其中空数组作为依赖项的选项。

我什至从 jsonplaceholder 检索数据,它没有设置使用状态。它显示空数组,这是初始值。

有时它会在我保存代码时更新,但在我刷新页面后它会消失并且不会更新 我又试了很多次

但问题是 react-dev-tools 显示状态更新值,即所有帖子。 但 'console.log() ' 不显示数据。

告诉为什么 setposts() 方法似乎没有设置状态,

import React,{ useEffect,useState} from 'react'

export default function Test() {

    const [ posts, setposts] = useState([]);

    useEffect(()=>{

        fetch('https://jsonplaceholder.typicode.com/posts',{

            method:'get',
    
        }).then(result=>{
            return result.json();
        }).then((data)=>{
            console.log(data);
            setposts(data);
        
            console.log(posts);
        })

    },[])

    return (
        <div>

               
        </div>
    )
}

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    useState API 没有像 React 类中的 setState 那样的回调。等待状态更新完成的唯一方法就是使用 useEffect 挂钩,就像这样

    useEffect(()=>{
    
            fetch('https://jsonplaceholder.typicode.com/posts',{
    
                method:'get',
        
            }).then(result=>{
                return result.json();
            }).then((data)=>{
                console.log(data);
                setposts(data);
            
                console.log(posts);
            })
    
        },[data])
    

    【讨论】:

    • 我猜这是错误的,因为您正在观察数据的变化以进行 api 调用......使用 useEffect 而不传递要观察的数据将仅在安装组件时立即运行跨度>
    【解决方案2】:

    基本上react不会立即改变状态,见useState set method not reflecting change immediately

    如果你想看到状态真的改变了,试着渲染帖子,比如(糟糕的例子,我知道):

    ...
    return (
            <div>{JSON.stringify(posts)}</div>
        )
    

    【讨论】:

      【解决方案3】:

      您的代码是正确的,但状态没有立即放置,所以当您调用控制台日志时,该值还没有准备好,但如果您在 html 中显示该数据,那将不是问题

      在您的代码中进行了一些更改和少量组织

      export default Test = {
        const [ posts, setposts] = useState([]);
      
        useEffect(()=>{
            fetch('https://jsonplaceholder.typicode.com/posts')
            .then(result => result.json())
            .then((data)=>{
              console.log(data); // Will be written because you are already at the end of the promisse
              setposts(data);      
              console.log(posts); // Will be empty cuz the async load of state
            });
        },[])
      
        return (
          <>          
            {posts.map(post => (
              <ul>
                <li key="{post.id}">{post.title}</li>
              </ul>
            ))}    
          </>
        )
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-12
        • 1970-01-01
        • 1970-01-01
        • 2018-08-13
        • 1970-01-01
        • 2020-02-08
        • 2022-01-24
        • 2015-12-15
        相关资源
        最近更新 更多