Home > Back-end >  Why this function doesn't rendering in react
Why this function doesn't rendering in react

Time:12-13

first, Thank you for entering like here

i want to be able to use like this code, this code is rendering in react component but second code doesn't work ..

That's what i worder sir.

    function forFourMultiplyFour(_pictures) {

        if (_pictures.length === 0) {
            return '';
        }

        return <div
            style={{ display: 'flex', justifyContent: 'center' }}>{_pictures.map((el) => {
                return <div style={{ margin: '5px' }}>
                    <Img key={el.id} src={el.src} alt="picture"></Img>
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <div>{el.title}</div>
                        <div>생성일자</div>
                    </div>
                </div>;
            })}</div>;
    }
    function makeHowManyPage(count) {
        // 태그안에 함수로 또 다른 태그를 감싼다음에 forFourMultiplyFour로 한 것처럼 렌더링할 것을 return 했는데
        // 안되서 state을 배열로 만들어서


        return <div
            className="makeHowManyPage"
            style={{ display: 'flex', justifyContent: 'center' }}>
            {() => {
                for (let i = 1; i <= count; i  ) {
                    return <div>{i}</div>
                }
            }}
        </div>
    }

and then i do render like this

import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import dummyPictures from '../../../dummyDate';

function Gallery() {

    const [forRenderingOne, setForRenderingOne] = useState(<div></div>);
    const [forRenderingTwo, setForRenderingTwo] = useState(<div></div>);
    const [forRenderingThree, setForRenderingThree] = useState(<div></div>);
    const [forRenderingFour, setForRenderingFour] = useState(<div></div>);
    const [pageCount, setPageCount] = useState(<div>1</div>);
    const [_temp, set_Temp] = useState(['안녕하세요', '안녕하세요', '안녕하세요', '안녕하세요'])

    // 애초에 4개씩 받아서 뿌릴 것

    function forFourMultiplyFour(_pictures) {

        if (_pictures.length === 0) {
            return '';
        }

        return <div
            style={{ display: 'flex', justifyContent: 'center' }}>{_pictures.map((el) => {
                return <div style={{ margin: '5px' }}>
                    <Img key={el.id} src={el.src} alt="picture"></Img>
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <div>{el.title}</div>
                        <div>생성일자</div>
                    </div>
                </div>;
            })}</div>;
    }

    function makeHowManyPage(count) {
        // 태그안에 함수로 또 다른 태그를 감싼다음에 forFourMultiplyFour로 한 것처럼 렌더링할 것을 return 했는데
        // 안되서 state을 배열로 만들어서


        return <div
            className="makeHowManyPage"
            style={{ display: 'flex', justifyContent: 'center' }}>
            {() => {
                for (let i = 1; i <= count; i  ) {
                    return <div>{i}</div>
                }
            }}
        </div>
    }

    useEffect(() => {
        // 서버에서 줄때 무조건 객체 16개가 든 배열이 응답해와야 정상작동되는 코드다..
        setPageCount(makeHowManyPage(5))

        setForRenderingOne(forFourMultiplyFour(dummyPictures.pictures.slice(0, 4)));
        setForRenderingTwo(forFourMultiplyFour(dummyPictures.pictures.slice(4, 8)));
        setForRenderingThree(forFourMultiplyFour(dummyPictures.pictures.slice(8, 12)));
        setForRenderingFour(forFourMultiplyFour(dummyPictures.pictures.slice(12)));

    }, []);

    return (
        <div>
            {/* {forRenderingOne}
            {forRenderingTwo}
            {forRenderingThree}
            {forRenderingFour} */}
            
            {()=>{ return <div>'안녕하세요'</div>}}
        </div>
    )
}

export default Gallery

const Img = styled.img`
    width: 15vw;
    height: 20vh;
`

CodePudding user response:

As stated this code snippet not working,

    function makeHowManyPage(count) {
        // 태그안에 함수로 또 다른 태그를 감싼다음에 forFourMultiplyFour로 한 것처럼 렌더링할 것을 return 했는데
        // 안되서 state을 배열로 만들어서


        return <div
            className="makeHowManyPage"
            style={{ display: 'flex', justifyContent: 'center' }}>
            {() => {
                for (let i = 1; i <= count; i  ) {
                    return <div>{i}</div>
                }
            }}
        </div>
    }

Have a look at this snippet returning div not array,

for (let i = 1; i <= count; i  ) {
   return <div>{i}</div>
}

map works differently.

Consider changing this to,


 function makeHowManyPage(count) {
    // 태그안에 함수로 또 다른 태그를 감싼다음에 forFourMultiplyFour로 한 것처럼 렌더링할 것을 return 했는데
    // 안되서 state을 배열로 만들어서

    let array = [];
    for (let i = 1; i <= count; i  ) {
      array.push(<div key={i}>{i}</div>);
    }

    return (
      <div
        className="makeHowManyPage"
        style={{ display: "flex", justifyContent: "center" }}
      >
        {array}
      </div>
    );
  }


Then usage,

export default function App() {
  
  // declaration

  let elements = makeHowManyPage(5);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      {elements}
    </div>
  );
}

CodePudding user response:

I don't understand what you exactly wanted, I just write some code that I expected to solve your problem. I hope it can help your problem though it is not the best solution.

First, I divide Gallery component into two components including your forFourMultiplyFour function.

(I don't have dummy pictures, so I used a picture list api for this.)

Second, as windowsill's comment, write simple value for the useState initial value. I think you only need two values, pages and images array. Usually people get the image list changing page and offset value not slicing image array. (If I have a wrong idea, please let me know.) So I just change page state when clicking button.

For 4*4 image arrangement, I used flex property.

import React, { useState, useEffect } from "react";
import axios from "axios";
import ForFourMultiplyFour from "./ForFourMultiplyFour";

function Gallery() {
  const [page, setPage] = useState(1);
  const [images, setImages] = useState([]);
  const URL = "https://picsum.photos/v2/list";
  const LIMIT = 16;

  useEffect(() => {
    async function fetchImages() {
      const { data } = await axios.get(`${URL}?page=${page}&limit=${LIMIT}`);
      setImages(data);
    }
    fetchImages();
  }, [images, page]);

  useEffect(() => {
    setPage(page)
  }, [page])

  return <ForFourMultiplyFour images={images} page={page} setPage={setPage} />;
}

export default Gallery;


import styled from "styled-components";

function ForFourMultiplyFour({ images, setPage, page }) {
  const handlePage = (param) => {
    if (param === "plus") {
      setPage(page   1);
    } else {
      if (page === 1) return;
      setPage(page - 1);
    }
  };
  if (images.length < 1) return <></>;
  return (
    <>
      <ButtonWrapper>
        <Button onClick={() => handlePage("minus")}>prev</Button>
        <Button onClick={() => handlePage("plus")}>next</Button>
      </ButtonWrapper>
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          flexWrap: "wrap"
        }}
      >
        {images.map((el) => {
          return (
            <div style={{ margin: "5px", flex: "1 1 20%" }} key={el.id}>
              <Img key={el.id} src={el.download_url} alt="picture"></Img>
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <div>생성일자</div>
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
}

const Img = styled.img`
  width: 15vw;
  height: 20vh;
`;

const ButtonWrapper = styled.div`
  display: flex;
`;

const Button = styled.button`
  cursor: pointer;
`;

export default ForFourMultiplyFour;

You can see the result through this Code Sandbox link.

If it is not a solution that you wanted, please comment me. Then I'll try to help you using another solution.

  • Related