我有一个Stepper组件,可以接收称为step的道具
export default function HorizontalLinearStepper({ step }) {
const classes = useStyles()
const [activeStep, setActiveStep] = React.useState(0)
const steps = getSteps()
return (
<div className={classes.root}>
<Stepper
activeStep={step}
connector={<ColorlibConnector />}
alternativeLabel
>
{steps.map(label => (
<Step key={label}>
<StepLabel
StepIconProps={{
classes: { root: classes.stepIcon },
}}
>
{label}
</StepLabel>
</Step>
))}
</Stepper>
</div>
)
}
我需要根据我的脚步道具来设置属性activeStep,如下所示:
if (step === 0) {
setActiveStep(0)
} else if (step === 1) {
setActiveStep(0)
} else if (step === 2) {
setActiveStep(2)
} else if (step === 3) {
setActiveStep(3)
} else if (step === 4) {
setActiveStep(4)
} else if (step === 5) {
setActiveStep(4)
}
上面的代码抛出错误: “太多的重新渲染。React限制了渲染数量以防止无限循环。”
最好的方法是什么?
答案 0 :(得分:1)
您应该使用useEffect对step
中的任何更改做出反应(不要打扰):
export default function HorizontalLinearStepper({ step }) {
const classes = useStyles()
const [activeStep, setActiveStep] = React.useState(step)
const steps = getSteps()
React.useEffect(() => {
setActiveStep(step)
}, [step])
return (
<div className={classes.root}>
<Stepper
activeStep={step}
connector={<ColorlibConnector />}
alternativeLabel
>
{steps.map(label => (
<Step key={label}>
<StepLabel
StepIconProps={{
classes: { root: classes.stepIcon },
}}
>
{label}
</StepLabel>
</Step>
))}
</Stepper>
</div>
)
}
不知道您getSteps
来自哪里,也许您也应该在道具中传递它。
答案 1 :(得分:1)
天哪,愚蠢的我。
我的步进器组件不需要其他状态,我可以像这样操作步进道具(虽然不是很令人满意,但是可以正常工作)
export default function HorizontalLinearStepper({ step }) {
const classes = useStyles()
const steps = getSteps()
if (step === 0) {
step = 0
} else if (step === 1) {
step = 0
} else if (step === 2) {
step = 1
} else if (step === 3) {
step = 2
} else if (step === 3) {
step = 2
} else if (step === 4) {
step = 3
} else if (step === 5) {
step = 4
} else if (step === 6) {
step = 4
}
return (
<div className={classes.root}>
<Stepper
activeStep={step}
connector={<ColorlibConnector />}
alternativeLabel
>
{steps.map(label => (
<Step key={label}>
<StepLabel
StepIconProps={{
classes: { root: classes.stepIcon },
}}
>
{label}
</StepLabel>
</Step>
))}
</Stepper>
</div>
)
}