Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

reactjs - While iterating the array, the records are not completely displaying in react hooks page

While iterating using map function in react-hooks, array data is not properly displaying in the page, I could see the array has got 3 records, but while iterating it is displaying only two records and that too same image got displayed twice. Could someone please help me to identify the issue here ? I can see a warning error logged in console: enter image description here enter image description here enter image description here

import React, { useRef, useEffect, useState } from "react";
const [dailyStatusPlayers, setDailyStatusPlayers] = useState([]);
const isMounted = useRef(false);

    useEffect(() => {
      isMounted.current = true;
      return () => isMounted.current = false;
    }, []);


    useEffect(() => {
        const fetchData = async () => {
          try {
            const res = await axios.get('http://localhost:8000/service/availability');
            if (isMounted.current) {
               setDailyStatusPlayers(res.data.dailyStatus);
            }
          } catch (e) {
            console.log(e);
          }
        }
        fetchData();
      }, []);

   return (
        <div className="availability_wrapper">
         <h4>In: <span className="displayInCount">20</span></h4>
            <div className="wrap">
                <div className="container">
                    <div className="dailystatus_section">
                        <span className="playerdailyrecord">
                             <h4>Player Daily Status:</h4>
                            <div className="row">
                                {
                                dailyStatusPlayers.map(([{id, photo, position, dailystatus}]) =>(
                                <div key={id} className="playerdailyrecord_main">
                                <span className="dailstatus_playerphoto"><img className="dailstatus_playerImage" key={photo} src={photo}></img></span>
                                <span className="dailstatus" key={dailystatus}>{dailystatus}</span>
                                <span className="dailstatus_playerposition" key={position}>{position}</span>
                                </div>
                                ))        
                                }
                            </div>
                            <button className="OverlayDailyStatus" onClick={displayAvailabilityStatus}>Enter</button>
                        </span>
                    </div>
                </div>
            </div>
            <DailyStatusDialog
              onSubmit={onSubmit}
              open={deleteDialog}
              onClose={() => setDeleteDialog(false)}
            />
        </div>
    );
const Availability = () =>{
  
    const [team1, setTeam1] = useState([]);
    const [team2, setTeam2] = useState([]);
    const [deleteDialog, setDeleteDialog] = useState(false);
    const [playerId, setPlayerId] = useState("");
    const [helperText, setHelperText] = useState('');
    const loginUserEmail = localStorage.getItem('loginEmail');
    const [dailyStatusPlayers, setDailyStatusPlayers] = useState([]);
    const [teamData, setTeamData] = useState([]);
    //const [dailyinput, setDailyInput] = useState('');
    const [inCount, setInCount] = useState("");
    const isMounted = useRef(false);
    const c_day = moment().format('dddd');
    const c_date = moment().format('DD-MM-YYYY');

    useEffect(() => {
      isMounted.current = true;
      return () => isMounted.current = false;
    }, []);

    const displayAvailabilityStatus = () =>{
       setDeleteDialog(true);
    }
     
    useEffect(() => {
        const fetchData = async () => {
          try {
            const res = await axios.get('http://localhost:8000/service/availability');
            if (isMounted.current) {
               setDailyStatusPlayers(res.data.dailyStatus[0]);
               //setTeamData(res.data.dailyStatus[0]);
               console.log("Complete array:"+res.data.dailyStatus[0]);
               
            }
          } catch (e) {
            console.log(e);
          }
        }
        fetchData();
      }, []);


      let i = 0;
      const tempTeam1 = [];
      const tempTeam2 = [];
      while(teamData.length > 0) {
        const random = Math.floor(Math.random() * teamData.length);
        i%2 === 0 ? tempTeam1.push(teamData[random]) : tempTeam2.push(teamData[random]);
        teamData.splice(random, 1);
        i++;
      }
    
      useEffect(() => {
      setTeam1(tempTeam1);
      setTeam2(tempTeam2);
      },[]);

   
    const onSubmit = (dailyinput) =>{
        console.log("Here Daily:"+ dailyinput);
        const dailyStatus = async () => {
            try {
                const params = {
                    email: loginUserEmail,
                };
              const res = await axios.post('http://localhost:8000/service/availability', { dailystatus: dailyinput }, {params} );
              console.log("Dailystatus update" + res.data.success);
              if (res.data.success) {
                setDeleteDialog(false);
              }
              else {
                console.log(res.data.message);
                setHelperText(res.data.message);
              }
            } catch (e) {
              setHelperText(e.response.data.message);
            }
          }
          dailyStatus();
    }

    return (
        <div className="availability_wrapper">
          <div className="displayCurrentDate">
            <b>{c_day}</b>, {c_date}
          </div>
         <h4>In: <span className="displayInCount">20</span></h4>
            <div className="wrap">
                <div className="container">
                    <div className="dailystatus_section">
                        <span className="playerdailyrecord">
                             <h4>Player Daily Status:</h4>
                            <div className="row">
                                {
                                dailyStatusPlayers.map(({id, photo, position, dailystatus}) =>(
                                <div key={id} className="playerdailyrecord_main">
                                <span className="dailstatus_playerphoto"><img className="dailstatus_playerImage" key={photo} src={photo}></img></span>
                                <span className="dailstatus" key={dailystatus}>{dailystatus}</span>
                                <span className="dailstatus_playerposition" key={position}>{position}</span>
                                </div>
                                ))        
                                }
                            </div>
                            <button className="OverlayDailyStatus" onClick={displayAvailabilityStatus}>Enter</button>
                        </span>
                    </div>
                </div>
                <div>
                    <div className="container">
                        <div className="playerdistribution_section">
                            <h4>Team Selection</h4>
                            <div className="wrap">
                                    <div className="left_col">
                                        {
                                        team1.map(({id, name, image}) =>(
                                        <div>
                                             <span key={name}>{name}</span>
                                        </div>
                                        ))
                                      }
                                    </div>
                                    <div className="right_col">
                                        {
                                        team2.map(({id, name, image})=>(
                                          <div>
                                          <span key={name}>{name}</span>
                                          </div>
                                        ))
                                        }
                                    </div>
                                </div>
                        </div>
                    </div>
                    <div className="container">
                        <div className="weeklycount_graph_section">
                                <span className="avail_newImageback">
                                  <img className="avail_newsImagesection" src="images/greenplayer.png"></img>         
                              </span>
                        </div>
                    </div>
                </div>
            </div>
            <DailyStatusDialog
              onSubmit={onSubmit}
              open={deleteDialog}
              onClose={() => setDeleteDialog(false)}
            />
        </div>
    );

}
export default Availability;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is that the array passed in from the server is being duplicated. Until the code on the server is fixed, you can simply pass in the first value of the array by calling setDailyStatusPlayers(res.data.dailyStatus[0]) inside of the second useEffect.

Should also change dailyStatusPlayers.map(([{id, photo, position, dailystatus}]) to remove the wrapping array. So it should become dailyStatusPlayers.map(({id, photo, position, dailystatus}).

Here is a Codesandbox with a working example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...