【问题标题】:React-Redux Maximum call stack size exceeded when adding object to listReact-Redux 将对象添加到列表时超出最大调用堆栈大小
【发布时间】:2021-11-28 01:19:07
【问题描述】:

我正在创建一个简单的游戏响应应用程序,当我尝试将玩家添加到我的玩家列表时,它似乎正在创建一个无限循环,我不知道为什么。我尝试使用 useEffect 在初始加载时呈现播放器列表,但这并没有帮助,所以我现在将其删除以简化。有什么想法我可以做不同的事情吗?

App.js

import React, { useEffect } from 'react'
import {useDispatch, useSelector} from 'react-redux';
import './App.css';
import {setPlayerName, increaseCurrentPlayerId, decreaseCurrentPlayerId, addPlayerToList} from './redux/reducers/playerReducer';

function App() {
  const dispatch = useDispatch()
  const playerName = useSelector(state => state.playerName);
  const playerList = useSelector(state => state.playerList);
  const currentPlayerId = useSelector(state => state.currentPlayerId)
  

  // dispatch(addPlayerToList('Test'))
  const addPlayer = (player) => {

   dispatch(addPlayer(player))
   dispatch(setPlayerName(''))
  }

  const renderPlayerList = () => {
    if (playerList.length < 1) {
      return (
        <div>
          No Players
        </div>
      )
    } else {
      return (
        playerList.map(p => 
          <p>p.name</p>
          )
      )
    }
  }

  return (
    <div className="App">
         <input 
          type='text'
          name='playerName' 
          onChange={({ target }) => dispatch(setPlayerName(target.value))}
          required
        />
          Name<br/>
            <button type='button' 
             onClick={() => addPlayer(playerName)}
             >
            Add Player</button> <br />
        <br />
    </div>
  );
}

export default App;

playerReducer.js

export const playerNameReducer = (state = '', action) => {
    switch (action.type) {
      case 'SET_PLAYER_NAME':
        return action.data;
      default:
        return state;
    }
  };

  export const playerListReducer = (state = null, action) => {
    switch (action.type) {
      case 'ADD_PLAYER':
        return [...state, action.data];
      default:
        return state;
    }
  };

动作创作者

  export const setPlayerName = playerName => {
    return {
      type: 'SET_PLAYER_NAME',
      data: playerName,
    };
  };
  
  export const addPlayerToList = player => {
    return {
      type: 'ADD_PLAYER',
      data: player,
    };
  };
  

【问题讨论】:

    标签: react-redux callstack


    【解决方案1】:

    addPlayer 调用自己

    const addPlayer = (player) => {
    
       dispatch(addPlayer(player))
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      • 2015-10-24
      • 2015-12-29
      • 2017-12-27
      • 2020-12-06
      相关资源
      最近更新 更多