• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

안녕하세요 개발자님

20.11.16 00:20 작성 조회수 78

0

안녕하세요 질문이 있는데요!

제가 개발자님의 코드를 적용하여 다른걸 만들어봤는데 오류가 나서 질문드립니다.

import React, { useEffectuseState } from 'react';
import axios from "axios";
import { IconColCardRowCarousel } from 'antd';
import Meta from 'antd/lib/card/Meta';
import ImageSlider from '../../utils/ImageSlider';
import SearchFeature from './Sections/SearchFeature';


const LandingPage = () => {

    const [ProductssetProducts] = useState([]);
    const [SkipsetSkip] = useState(0);
    const [LimitsetLimit] = useState(8);
    const [SearchTermsetSearchTerm] = useState("");
    const [scoresetScore] = useState(0);
        

    const getProducts = (body=> {
        axios.post('/api/product/products'body)
            .then(response => {
                if (response.data.success) {
                    setProducts(response.data.productInfo)
                    
                } else {
                    alert(" 상품들을 가져오는데 실패 했습니다.")
                }
            })
    }

    const renderCards =  Products.map((productindex=> {
        console.log('*** : 'product)
        const title  = product.title ?? '';
        
        const splitTitle = title.split(',');
        
        var _score = 0;

        const temp = splitTitle.map((stri=> {
            const _str = str;    
         
            if(_str === '철' || _str === '금' || _str === '불'){
                _score += 1;
            }
        });

        console.log('_score : ',_score)
     
       setScore(_score) <<< 이부분

        return <>
            <Col lg={6} md={8} xs={24} key={index }>
                <Card
                    cover={<a href={`/product/${product._id}`} ><ImageSlider images={product.images} /></a>}
                >
                    <Meta
                        title={product.description}
                        // description={`$${product.description}`}
                    />
                </Card>
            </Col>
        </>
    })
    

    const updateSearchTerm = (finalSearch=> {
         console.log("finalSearch",finalSearch);
        let body = {
            skip: 0,
            limit: Limit,
            searchTerm: finalSearch
           
        }
        setSkip(0)
        setSearchTerm(finalSearch)
        getProducts(body)
    }

   
    return (

        <div style={width: '75%'margin: '3rem auto' }}>
            <div style={textAlign: 'center' }}>
                <h2>Let's Travel Anywhere <Icon type="rocket" /> </h2>
            </div>


            <div style={display: 'flex'justifyContent: 'flex-end'margin: '1rem auto' }}>
                {/* <SearchFeature
                    refreshFunction={ updateSearchTerm}
                />
            </div> */}

            <SearchFeature
                   updateSearchTerm={filters => updateSearchTerm(filters)}
                />
            </div>
    

            <Row gutter={[1616]} >
                {renderCards}
            </Row>

            <br />

           
        </div>
    )
}

export default LandingPage

import React, { useEffectuseState } from "react";
import { Input } from "antd";

const { Search } = Input;

function SearchFeature(props) {
  const [searchTermsetSearchTerm] = useState({
    s1: "",
    s2: "",
    s3: "",
  });
  console.log("searchTerm :::"searchTerm);
  const searchHandler = (keydata=> {
    setSearchTerm({
      ...searchTerm,
      [key]: data,
    });
  };

  const onSubmitHandler = (event=> {
    event.preventDefault();
    const postData = searchTerm;
    //if(예외처리)
    props.updateSearchTerm(postData);
  };

  return (
    <div>
      <form onSubmit={onSubmitHandler}>
        <div>
          <Search
            placeholder="ingredients1"
            onChange={(e=> searchHandler("s1"e.target.value)}
            style={width: 200 }}
            value={searchTerm.s1}
          />
        </div>
        <div>
          <Search
            placeholder="ingredients2"
            onChange={(e=> searchHandler("s2"e.target.value)}
            style={width: 200 }}
            value={searchTerm.s2}
          />
        </div>
        <div>
          <Search
            placeholder="ingredients3"
            onChange={(e=> searchHandler("s3"e.target.value)}
            style={width: 200 }}
            value={searchTerm.s3}
          />
        </div>
        <button>변신!</button>
      </form>
    </div>
  );
}

export default SearchFeature;



제가 이것을 응용해봤는데요 제가 하려는 것은  제가 입력한 세개의 값이 만약 철 금 불 이라고 가정했을 시 디비에 철 금 불 이라는 글자가 있을때 제가 입력한 글과 디비에 있는 글이 맞은 수 대로 score에 setScore를 통해서 저장해주려고 하거든요.. 값은 잘 들어오고 console에도 값이 맞은 글자 수 대로 잘 들어옵니다 이것 말고는 다른페이지의 코드도 거의 같습니다. 그런데 setScore(_score)를 하여 state값에 스코어를 저장하려하면 이상하게  콘솔에 수많은 score값이 찍히며 Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

이러한 에러가 뜹니다... 이것을 해결하려면 어떻게 해야할까요...

답변 0

답변을 작성해보세요.

답변을 기다리고 있는 질문이에요.
첫번째 답변을 남겨보세요!