【发布时间】:2019-10-27 23:48:18
【问题描述】:
示例是使用 useState 来保持点击计数器的简单功能组件。
逐步通过 Stepper MUI 组件,我想创建具有不同初始化值的示例组件的实例,例如在步骤 0,初始值 100,在步骤 1,初始值 111,在步骤 2,初始值 112。
在逐步执行每个步骤时,尽管传递了不同的初始值,示例功能组件仅将状态保持到第一个初始值,即 100。
文件是 /Components/Navigation/Stepper01a.js,在 StepContent 中引用的示例组件,在 HorizontalLinearStepper 组件中引用。整体代码来自 Material UI Stepper 组件的示例。我只是试图测试它以在每个步骤中创建具有不同初始值的其他功能组件的不同实例(在本例中为示例)。
示例组件:
function Example({ init }) {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = React.useState(init)
return (
<div>
<p>init {init} </p>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
)
}
StepContent 组件:
function StepContent({ step }) {
console.log("step", step)
switch (step) {
case 0:
return <Example init={100} />
case 1:
return <Example init={111} />
case 2:
return <Example init={112} />
default:
return "Unknown step"
}
}
HorizontalLinearStepper 组件:
export default function HorizontalLinearStepper() {
...
<div>
<StepContent step={activeStep} />
</div>
...
}
查看运行示例https://mj3x4pj49j.codesandbox.io/ 代码https://codesandbox.io/s/mj3x4pj49j
在第 0 步单击下一步时,count 应设置为初始值 111,但仍为 100;在第 1 步单击下一步时,count 应设置为初始值 112,但仍为 100。似乎一旦在第 0 步将状态计数初始化为 100,则在第 1 步和第 2 步中使用相同的状态,即状态不是孤立的。
这个问题是不是因为违反了 Hooks 规则?
【问题讨论】:
标签: reactjs react-hooks