【发布时间】:2021-07-06 02:36:53
【问题描述】:
在这里展示我的问题是一个演示代码。(我正在使用 React Hooks 和 Antd。)
我的问题是:
当currId 状态改变并且我单击MyButton 时,状态仍然是''(这是初始状态)。 onClick 事件是一个箭头函数,其中showModal 带有参数,如果没有参数currId 可以看到更改,但现在参数状态没有更改。请问是什么原因造成的,如何将currId改成showModal?
(操作:点击'Change CurrId'按钮 --> setCurrId('12345') ---> 点击'MyButton' ---> console.log(currId))
import React, { useState } from 'react'
import 'antd/dist/antd.css';
import { Button} from 'antd';
const MyComponent= () => {
const [currId, setCurrId] = useState('');
const changeCurrId= async () => {
setCurrSolutionId('12345');
}
const showModal = async (num:any) => {
console.log("☆ currid:");// I cannot get the currId state '12345' but ''
console.log(currId);
console.log("☆ num:");//I can get the num params 5
console.log(num);
};
return (
<>
<Button type="primary" onClick={changeCurrId}>Change CurrId</Button>
<Button type="primary" onClick={() => {showModal(5)}}>MyButton</Button>
</>
);
}
【问题讨论】:
-
您是如何更改
currId的?您没有调用setCurrId来更新currId的值。 -
我在单击另一个未显示的按钮时更改了我的 currId。 (在它的onclick事件中我用setCurrId(“12345”)改变了状态)
-
const MyComponent= () => { const [currId, setCurrId] = useState(''); const showModal = async () => { console.log("☆ currid:"); console.log(currId); }; return ( <Button type="primary" onClick={showModal}>MyButton</Button> ); }上面的代码可以通过控制台记录更改的 currId 但使用 params(showModal(5)) 不能... -
能否也包含更改状态的代码?
-
const MyComponent= () => { const [currId, setCurrId] = useState(''); const changeCurrId= async () => { setCurrSolutionId('12345'); } const showModal = async (num:any) => { console.log("☆ currid:"); console.log(currId); }; return ( <Button type="primary" onClick={changeCurrId}>Change CurrId</Button> <Button type="primary" onClick={() => {showModal(5)}}>MyButton</Button> ); }整个结构是这样的。
标签: reactjs react-hooks