[英]Clear button in React clears input but doesn't reset the array element
I try to make a simple meme generator where a user can add a text and change the image on click.我尝试制作一个简单的模因生成器,用户可以在其中添加文本并在单击时更改图像。 Both is working but my clear-button only clears the input field and don't get back to the first image (array[o]).
两者都在工作,但我的清除按钮仅清除输入字段并且不会返回到第一张图像(数组 [o])。 I mean if I conole.log the "element" it says "0" but it don't change the image to the first one.
我的意思是如果我 conole.log “元素”它说“0”但它不会将图像更改为第一个。
My code of App.js so far:到目前为止我的 App.js 代码:
import React, { useEffect, useState } from "react";
import "./styles.css";
function useCounter(initialCount = 0) {
const [count, setCount] = React.useState(initialCount);
const increment = React.useCallback(() => setCount((c) => c + 1), []);
return { count, increment };
}
export default function App() {
let { count: element, increment } = useCounter(0);
const [memes, setMemes] = useState([]);
const [topText, setTopText] = useState("");
useEffect(() => {
async function asyncFunction() {
const initialResponse = await fetch("https://api.imgflip.com/get_memes");
const responseToJSON = await initialResponse.json();
setMemes(responseToJSON.data.memes);
}
asyncFunction();
}, []);
const clear = (e) => {
setTopText("");
element = 0;
console.log(element);
};
return (
<div className="App">
{memes[0] ? (
<div
style={{
height: "300px",
backgroundImage: `url(${memes[element].url})`
}}
>
<p>{topText}</p>
<input
value={topText}
onChange={(e) => setTopText(e.target.value)}
type="text"
/>
<button onClick={clear} type="reset">Clear</button>
<button onClick={increment}>Change Image</button>
</div>
) : (
"loading"
)}
</div>
);
}
What is wrong?怎么了?
You are attempting to mutate state. You should never directly assign a new value to a stateful variable element = 0
.您正试图改变 state。您永远不应直接将新值分配给有状态变量
element = 0
。 You should use the provided updater function from useState
( setCount
).您应该使用
useState
( setCount
) 提供的更新程序 function。
One solution would be to add a reset function to your custom hook and use it:一种解决方案是将重置 function 添加到您的自定义挂钩并使用它:
function useCounter(initialCount = 0) {
const [count, setCount] = React.useState(initialCount);
const increment = React.useCallback(() => setCount((c) => c + 1), []);
const reset = () => setCount(initialCount);
return { count, increment, reset };
}
In your component:在您的组件中:
const { count: element, increment, reset: resetCount } = useCounter(0);
const clear = (e) => {
setTopText("");
resetCount();
};
Notice I've also changed the custom hook to use a const
instead of let
.请注意,我还更改了自定义挂钩以使用
const
而不是let
。 This is recommended to encourage immutable usage of state, and give helpful errors when breaking that rule.建议这样做以鼓励 state 的不可变使用,并在违反该规则时给出有用的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.