gpt4 book ai didi

reactjs - 使用 React.js 设置 useContext 和 useState 的正确方法?

转载 作者:行者123 更新时间:2023-12-03 14:22:06 25 4
gpt4 key购买 nike

我有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.Provider 的组件(RoomPage)中使用 RoomContext,该组件位于层次结构的较高位置,因为它在组件内呈现。

此处使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com