React Hooks中的useState()设置器不起作用

时间:2020-10-12 12:49:23

标签: reactjs react-hooks

我有一个名为useAddFriend的自定义钩子,下面是代码:

import { useCallback, useState } from 'react'
import { Users }from '../data/userDummy'

const useAddFriend = () => {
    const [roomId, setRoomId] = useState("default")

    const findUser = useCallback((username) => {
        for(let user of Users) {
            if(username === user.username) {
                setRoomId("newRoomId")
            }
        }
    }, [])

    return { roomId, findUser }
}

export default useAddFriend;

问题在于,setRoomId从不更新roomId。我已经确定它满足上面的if condition。但是它总是返回default

这是我在React组件上使用钩子的方式:

const AddFriend = () => {
    const [username, setUsername] = React.useState('')
    const { roomId, findUser } = useAddFriend()
    const history = useHistory()

    const handleInputChange = (event) => {
        setUsername(event.target.value)
    }
    
    const handleAddFriend = () => {
        findUser(username)
        setUsername("")
        history.push(`/${roomId}`)
    }

    ...
}

2 个答案:

答案 0 :(得分:1)

我认为原因在这里:

const handleInputChange = (event) => {
    setUsername(event.target.value)
}

const handleAddFriend = () => {
    findUser(username)
    setUsername("")
    history.push(`/${roomId}`) // <= This line may execute before the roomId is fully set
}

为确保执行钩子后获得正确的roomId,建议与useEffect一起使用

const handleAddFriend = () => {
    findUser(username)
    setUsername("")
}

useEffect(()=> { if(roomId!=='default') history.push(`/${roomId}`) }, [roomId]);

答案 1 :(得分:0)

您需要删除useCallback或在方括号中传递要更新的参数

const findUser = useCallback((username) => {
    for(let user of Users) {
        if(username === user.username) {
            setRoomId("newRoomId")
        }
    }
}, [roomId])