简体   繁体   中英

React - Redux State update but not rendered in the component

I have a component Details.js where i am populating teams from 4 Leagues in a Select Dropdown

Depending on the team selected the states in State.js component are updated

The problem is that depending from the team selected, sometimes the state is rendered in State.js and sometimes no.

There are not errors in the console and in the redux tool the states are updated correctly.

I am using https://www.api-football.com/ to consume the data.

Here the relevant code

In the reducers/index.js i have created an initial state

RECEIVE_LEAGUE
  league:[],

case RECEIVE_LEAGUE:
  return {...state, leagueId: action.json};

In the actions/index.js

export const receivedLeague = json => ({
  type: RECEIVE_LEAGUE,
  json: json
});

I have added a dispatch in the getTeamsDetailById(id)

dispatch(receivedLeague(id));

In the Details.js component

I have added the state leagueId on top

and edited my selectTeamStat function

  const [selectedOption, setSelectedOption] = useState('');

  const selectTeamStat = (evt) => {
     const { value } = evt.target;
     setSelectedOption(value)
     getStats(leagueId, value);
  };

I have provided the demo in codesandbox reproducing the case here ( It is necessary to use Google Chrome extension CORS Unblock to see or any other extension unblocking the CORS )

To reproduce the case for example select Flamengo in Serie A and the state is updated and not rendered in the component but if you select Botafogo it is rendered. Why?

if (
  teamsStatsWinHome !== null && // maybe you also need to add `typeof object === 'undefined'`
  teamsStatsWinAway !== null &&
  teamsStatsDrawHome !== null &&
  teamsStatsDrawAway !== null &&
  teamsStatsLoseHome !== null &&
  teamsStatsLoseAway !== null
)

to avoid repetition you can also use but maybe the first way is easier to read

const isNullOrUndefined = (object) => object === null || typeof object === 'undefined';

if(![
  teamsStatsWinHome,
  teamsStatsWinAway,
  teamsStatsDrawHome,
  teamsStatsDrawAway,
  teamsStatsLoseHome,
  teamsStatsLoseAway,
].some(isNullOrUndefined))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM