[英]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.我有问题,我从 React 中的 Hooks 方法开始,我有一个输入搜索,当我按下“Enter”键时,这会加入一个设置值的函数。 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.
问题是当我尝试返回值时,在这种情况下,console.log("hi") 被打印两次,我不知道为什么会发生这种情况,我尝试使用条件运算符,但它总是呈现两次。
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.
更新后您应该会看到 1 个以上的控制台日志。 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我希望这可以帮助你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.