我有contexts/RoomContext.tsx

import { useState, createContext } from 'react';

const RoomContext = createContext([{}, () => {}]);

const RoomProvider = (props) => {
    const [roomState, setRoomState] = useState({ meetingSession: null, meetingResponse: {}, attendeeResponse: {} })

    return <RoomContext.Provider value={[roomState, setRoomState]}>
        {props.children}
    </RoomContext.Provider>
}
export { RoomContext, RoomProvider }


然后在我的组件RoomPage.tsx中,我有:

const RoomPageComponent = (props) => {
    const router = useRouter()
    const [roomState, setRoomState] = useContext(RoomContext);

    useEffect(() => {
        const createRoom = async () => {
            const roomRes = await axios.post('http://localhost:3001/live')
            console.log('roomRes', roomRes)
            setRoomState(state => ({ ...state, ...roomRes.data }))
        }

        if (router.query?.id) {
            createRoom()
        }

    }, [router])

    return <RoomPageWeb {...props} />
}

export default function RoomPage(props) {

    return (
        <RoomProvider>
            <RoomPageComponent {...props} />
        </RoomProvider>
    )
}


但我收到有关setRoomState的投诉:

This expression is not callable.
  Type '{}' has no call signatures.

最佳答案

这里的问题是,您试图在不具有RoomContext的组件(RoomPage)中使用RoomContext.Provider,因为该组件在组件中呈现,因此在层次结构中更高。

此处用RoomProvider包装RoomPage的解决方案



import { RoomProvider, RoomContext } from '../../contexts/RoomContext'
function RoomPage(props) {
    const [roomState, setRoomState] = useContext(RoomContext);

    useEffect(() => {
        const createRoom = async () => {
            const roomRes = await axios.post('http://localhost:3001/live')
            console.log('roomRes', roomRes)
            setRoomState(state => ({...state, ...roomRes.data}))

        }
    ...

    return (

            <RoomPageWeb {...props} />
    )

export default (props) => (
    <RoomProvider><RoomPage {...props} /></RoomProvider>
)

关于reactjs - 用React.js设置useContext和useState的正确方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61579848/

10-10 07:34