реагирует на хуки неверный вызов хука с контекстом - PullRequest
1 голос
/ 11 апреля 2020

Я пытаюсь написать простой компонент, который после рендеринга выбирает gameState из API и условно отображает соответствующий компонент. Я использую Context для сохранения состояния, но продолжаю получать неверный вызов ловушки, когда я вызываю диспетчер. [Введите описание изображения здесь] [1]

import React from 'react';
import './App.css';
import Landing from './Components/Landing/Landing';
import {PokerContext} from './DrawPokerContext';


const initialState = {
  token : null,
  pokerGame : false,
};

const reducer = (state, action) => {
  switch (action.type) {
    case "UPDATEGAME":
      localStorage.setItem("pokerGame", JSON.stringify(action.payload.pokerGame));
      localStorage.setItem("token", JSON.stringify(action.payload.token));
      return {
        token: action.payload.token,
        pokerGame: action.payload.pokerGame
      };

    case "SETGAME":
      localStorage.setItem("pokerGame", JSON.stringify(action.payload));
      return {
        pokerGame: action.payload,
        token: null
      };

    default:
      return state;
  }
};


function App() {
  const [state, dispatch] = React.useReducer(reducer, initialState);
  return (
    <PokerContext.Provider value = {{state, dispatch}}> 
    <div>
    <Landing /> 
    </div>
    </PokerContext.Provider>
  );
}

export default App;

import React, {useEffect, useState} from 'react';
import {PokerContext} from '../../DrawPokerContext';
import PlayerLanding from './PlayerLanding';
import AdminLanding from './AdminLanding';
import axios from 'axios';



const Landing = () => {
const {state, dispatch} = React.useContext(PokerContext);
const [isFetched, setFetched] = useState(false);

useEffect(() => {
    fetchGame();
}, []);

async function fetchGame() {
    axios.get('http://localhost:5000/api/game/board').then(res => {
    return res.data.game;   
}).then(game => {
    dispatch({
        type: "SETGAME",
        payload: game,
    });
    return game;
}).then(() => {
   setFetched(true);
});
};

// if no game was found
if (state.pokerGame === false ) {
    return "Loading";
}    

// if there is no admin in the game
else {
    if (!state.pokerGame.adminName) {
        return <AdminLanding />;
    }
    return <PlayerLanding />;
   }
}
export default Landing;

import React from 'react';

export const PokerContext = React.createContext();

  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-loading": "^2.0.3",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.1"
  },

Это ошибка, которую я получаю и которую не могу устранить. Я проверил, что существует только одна версия React, и response / response-dom имеют ту же версию, поэтому я не совсем уверен, как устранить ошибку, которая показана ниже. Я очень новичок в React и буду признателен за любое понимание этого. Спасибо.

Сообщение об ошибке: Ошибка: неверный вызов ловушки. Хуки могут быть вызваны только внутри тела компонента функции.

  18 |     axios.get('http://localhost:5000/api/game/board').then(res => {
  19 |     return res.data.game;   
  20 | }).then(game => {
> 21 |     dispatch({
  22 |         type: "SETGAME",
  23 |         payload: game,
  24 |     });
...