简体   繁体   中英

console.log is rendered twice

i have problem, im starting with Hooks Methods in React, i have a input search that when i press the key "Enter", this join into a function that set the value. the problem is when i try to return the value, in this case the console.log("hi") is printted twice, and i don't know why it is happening, i try with conditional operators, but it always renders twice.

import React, { useState } from "react";
import SearchAPI from "./SearchAPI";

export default function Search() {
  const searchRef = React.createRef();

  const [contentSearched, setContentSearched] = useState("");

  const handleSendSearch = e => {
    if (e.key === "Enter") {
      setContentSearched(searchRef.current.value);
    } else {
      setContentSearched("");
    }
  };

  return (
    <section className="searchbox-wrap">
      <input
        onKeyPress={handleSendSearch}
        ref={searchRef}
        placeholder="Search for a movie..."
        type="text"
        className="searchbox"
      />
      {contentSearched !== "" ? console.log("Hi") : <></>} -> Here i have the problem
    </section>
  );
}

Console

Hi Search.js:19 
Hi Search.js:19 

Thanks

try to create a more simple component like this. You should see more than 1 console log after update. I think that maybe there's no issue.

function Test() {
  const [clickedTimes, setClickedTimes] = React.useState(0);
  console.log('rendering')
  function clickHandler() {
    console.log('clicked triggered')
    setClickedTimes(clickedTimes + 1)
  }
  return <span onClick={clickHandler}>clicked: {clickedTimes}</span>
}

I hope this can help you

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