這是用戶界面

我單擊第一個按鈕,然后單擊第二個按鈕,它顯示值 1,但我希望它顯示值 2,因為我將值設定為 2。有什么問題,我應該如何解決這個問題?
這是代碼:
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import React, {
useState,
useEffect,
useMemo,
useRef,
useCallback
} from "react";
const App = () => {
const [channel, setChannel] = useState(null);
const handleClick = useCallback(() => {
console.log(channel);
}, [channel]);
const parentClick = () => {
console.log("parent is call");
setChannel(2);
};
useEffect(() => {
setChannel(1);
});
return (
<div className="App">
<button onClick={parentClick}>Click to SetChannel 2</button>
<button onClick={handleClick}>Click to ShowChannel 2</button>
</div>
);
};
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(<App />);
這是代碼框
uj5u.com熱心網友回復:
useEffect(() => {
setChannel(1);
});
在每次渲染時運行,所以它總是恢復到 1
uj5u.com熱心網友回復:
您的問題是每次渲染都將通道值設定為 1。您有 2 個選項。
- 將通道的初始狀態值設定為 1(見下文)
- 呼叫方法
this.setState({channel: 1})。componentDidMount
class App extends React.Component {
constructor(props) {
super(props);
this.state = {channel: 1};
}
handleClick=(evt)=> {
console.log(this.state.channel);
}
parentClick=(evt)=> {
this.setState({channel: 2});
}
render() {
return (
<div className="App">
<button onClick={this.parentClick}>Click to SetChannel 2</button>
<br /><br />
<button onClick={this.handleClick}>Click to ShowChannel 2</button>
</div>
);
}
}
PS:目前尚不清楚您要做什么,并且您的沙箱與您在此處發布的代碼完全不同。
uj5u.com熱心網友回復:
向useEffect鉤子添加依賴項,如果您不添加任何依賴項,它將在每次狀態更改時重新運行。
改變這個:
useEffect(() => {
setChannel(1);
});
對此:
useEffect(() => {
setChannel(1);
}, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/490697.html
標籤:javascript 反应 使用状态
上一篇:列出給定月份的每個日期
