Jaf*_*aei 8 javascript reactjs react-hooks
I want to call multi react hook
setter function together, when some event been triggered
Sth like :
const [running, setRunning] = useState(false);
const [jumping, setJumping] = useState(true);
Run Code Online (Sandbox Code Playgroud)
then what should we do, if we want to setRunning
and setJumping
together? (avoid re-render component)
您可以按如下顺序依次调用它们(demo):
const Comp = ({ flag }) => {
const [running, setRunning] = useState(false);
const [jumping, setJumping] = useState(false);
const setBoth = () => {
setRunning(true);
setJumping(true);
};
return (
<>
{"running: " + running}
{"jumping: " + jumping}
<button onClick={() => setBoth()}>setboth</button>
</>
);
};
Run Code Online (Sandbox Code Playgroud)
另外,您可以像这样同时设置它们:
const Comp = ({ flag }) => {
const [RJ, setRJ] = useState([false, false]);
const setBoth = () => {
setRJ([true, true]);
};
return (
<>
{"running: " + RJ[0]}
{"jumping: " + RJ[1]}
<button onClick={() => setBoth()}>setboth</button>
</>
);
};
Run Code Online (Sandbox Code Playgroud)
https://codesandbox.io/s/0pwnm2z94w
归档时间: |
|
查看次数: |
1793 次 |
最近记录: |