useContext值未定义

时间:2020-04-26 06:34:01

标签: reactjs

我仍在尝试使用useContext()钩子。

我有以下代码;

App.js

const initialPlayerStatus = {
    playerHealth: 5,
    playerCoins: 0,
    playerMoves: 0,
    currentLevel: 1,
}
const PlayerStatusContext = React.createContext(null);
export const usePlayerStatus = () => useContext(PlayerStatusContext);


export default () => {
    const [gameState, setGameState] = useState("MainMenu");
    const [playerStatus, setPlayerStatus] = useState(initialPlayerStatus);
    const updatePlayerStatus = newPlayerStatus => setPlayerStatus(newPlayerStatus);
    const GameComponent = APP_COMPONENTS[gameState];

    return (
        <Wrapper>
            <PlayerStatusContext.Provider value={playerStatus, updatePlayerStatus} >
                {GameComponent}
            </PlayerStatusContext.Provider>
        </Wrapper>
    )
}

GameComponent

export default () => {
    const {playerStatus, updatePlayerStatus} = usePlayerStatus();
    console.log(playerStatus);
    return (
        <Wrapper>
            <button onClick={() => {
                console.log(playerStatus)
            }}>Log status</button>

            <button onClick={() => {
                updatePlayerStatus({
                    playerHealth: 6,
                    playerCoins: 1,
                    playerMoves: 1,
                    currentLevel: 2,
                })
            }}>Update Test</button>
        </Wrapper>
    )
}

但是,第一个按钮返回未定义,第二个按钮返回updatePlayerStatus不是函数。

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

问题似乎是由您注入Provider的值引起的。考虑以下更改:

<PlayerStatusContext.Provider value={playerStatus, updatePlayerStatus}>

收件人:

<PlayerStatusContext.Provider value={{playerStatus, updatePlayerStatus}}>

请注意传递给{道具的值周围还有}value的额外集合。这样,您就可以将playerStatus对象和updatePlayerStatus函数合并到一个单独的value中,该usePlayerStatus()会传递到提供程序中。然后,可以通过adb devices钩子返回的值来正确地分解此组合值。

希望有帮助!