简体   繁体   English

settimeout 是返回 object 的所有值,为什么不只返回一个值?

[英]The settimeout is returning all values of the object, why is it not returning only one value?

const RequestStatus = () => {
    const status = 'SUCCESS'
    
    const object = {
        SUCCESS: console.log('Success'),
        PROGRESS: console.log('Progress'),
        ERROR: console.log('Errror'),
    }
   
    useEffect(() => {
        setTimeout(() => {
            return object[status]
        }, 5000)
    }, [status])
}

You see all three statuses logged because you are calling all console.log when you create your object您会看到记录了所有三种状态,因为您在创建 object 时正在调用所有 console.log

Here are two ways you can modify your code to fix this这里有两种方法可以修改你的代码来解决这个问题

In the first method (which is the one I recommend) I am mapping the messages to the status codes and getting the approprite message using object[status]在第一种方法(这是我推荐的方法)中,我将消息映射到状态代码并使用 object[status] 获取适当的消息

const RequestStatus = () => {
    const status = 'SUCCESS'
    
    const object = {
        SUCCESS: 'Success',
        PROGRESS: 'Progress',
        ERROR: 'Errror',
    }
   
    useEffect(() => {
        setTimeout(() => {
            console.log(object[status]);
        }, 5000)
    }, [status])
}

In the second one I create lambda functions for each status code that define what happens when that status code occurs在第二个中,我为每个状态代码创建了 lambda 函数,这些函数定义了发生该状态代码时会发生什么

const RequestStatus = () => {
    const status = 'SUCCESS'
    
    const object = {
        SUCCESS: ()=>{console.log('Success')},
        PROGRESS: ()=>{console.log('Progress')},
        ERROR: ()=>{console.log('Errror')},
    }
   
    useEffect(() => {
        setTimeout(() => {
            object[status]();
        }, 5000)
    }, [status])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM