我正面临一个问题与我的React上下文我尝试使用setState但状态值仍然未定义
Context.js
import {
createContext,
useContext,
useMemo,
useState,
useEffect
} from "react";
const PlayerGamepadContext = createContext();
export const PlayerGamepadProvider = ({
...props
}) => {
const [gamepads, setGamepads] = useState([])
const [gamepadsCount, setGamepadsCount] = useState(0)
const [mappedGamepads, setMappedGamepads] = useState([])
// Triggered when button state change
// (button: string, isPressed: bool, controllerIndex: integer) => void
const [onButtonStateChanged, setOnButtonStateChanged] = useState(undefined)
useEffect(() => {
console.log("STATE CHANGED")
console.log(setOnButtonStateChanged);
console.log(onButtonStateChanged); // This shouldn't be undefined after I call "setOnButtonStateChanged"
}, [onButtonStateChanged])
const value = useMemo(() => {
return {
gamepads,
mappedGamepads,
playerCount: mappedGamepads?.length,
setOnButtonStateChanged,
setOnGamepadConnected
}
}, [
gamepads,
mappedGamepads,
setOnButtonStateChanged,
setOnGamepadConnected
])
if (typeof window === 'undefined') {
return "Loading";
}
return <PlayerGamepadContext.Provider value={value} {...props} />
}
export const usePlayerGamepads = () => {
const context = useContext(PlayerGamepadContext)
return context
}
Component.jsx
import React, { useEffect } from 'react'
import { usePlayerGamepads } from '@/components/Context/PlayerGamepadContext'
const TestController = props => {
const [state, setState] = React.useState(undefined)
const [init, setInit] = React.useState(false)
const playerGamepads = usePlayerGamepads()
const handleChange = (button, isPressed, index) => {
console.log(button, isPressed, index);
};
useEffect(() => {
setState(playerGamepads)
if (playerGamepads && !init) {
setInit(true)
console.log("CALL SET STATE");
playerGamepads.setOnButtonStateChanged(handleChange)
}
}, [playerGamepads]);
return (
<div></div>
)
}
export default TestController
下面是控制台输出
1- CALL SET STATE
2- undefined undefined undefined
3- STATE CHANGED
4- ƒ dispatchSetState(fiber, queue, action) {........
5- undefined
我有点困惑,为什么我的handleChange函数在使用setOnButtonStateChanged
(输出行2)后调用但更重要的是,为什么onButtonStateChanged
在改变后仍然未定义?
我试着通过PlayerGamepadProvider道具传递一个函数,它工作了,但我需要能够从状态设置它。
我也试图给onButtonStateChanged
一个默认值
const [onButtonStateChanged, setOnButtonStateChanged] = useState(console.log)
但是它直接取未定义的值而不是
提前感谢您的帮助
您正在将handleChange
的结果设置为OnButtonStateChanged
,这就是为什么调用控制台日志并且结果未定义的原因。
代替:
playerGamepads.setOnButtonStateChanged(handleChange)
试题:
playerGamepads.setOnButtonStateChanged(() => handleChange)