【发布时间】:2021-08-16 12:32:06
【问题描述】:
我有一个父组件和两个子组件,如下所示:
父组件:
import React, { useState } from "react";
import { Child1Comp } from "./Child1Comp";
import { Child2Comp } from "./Child2Comp";
export function ParentComp() {
const [step, setStep] = useState(1);
const [parentState, setParentState] = useState({});
const handleNextBtn = () => setStep((step) => step + 1);
const handlePrevBtn = () => setStep((step) => step - 1);
return (
<div>
<div>{`the parent state is: ${JSON.stringify(parentState)}`}</div>
{step === 1 && (
<Child1Comp
step={step}
parentState={parentState}
setParentState={setParentState}
/>
)}
{step === 2 && (
<Child2Comp
step={step}
parentState={parentState}
setParentState={setParentState}
/>
)}
<br />
<button
id="nextBtn"
name="nextBtn"
onClick={handleNextBtn}
disabled={step === 2}
>
Next
</button>
<button
id="nextBtn"
name="nextBtn"
onClick={handlePrevBtn}
disabled={step === 1}
>
Prev
</button>
<br />
<br />
{`current step is : ${step}`}
</div>
);
}
Child1Component:
import React, { useEffect, useState } from "react";
export function Child1Comp({ step, parentState, setParentState }) {
const [inputValue, setInputValue] = useState();
const handleChange = (e) => setInputValue(e.target.value);
useEffect(() => setInputValue(parentState.child1), []);
useEffect(
() =>
setParentState((parentState) => ({
...parentState,
child1: inputValue
})),
[step]
);
return (
<div>
<br />
name:
<input
id="child1"
name="child1"
value={inputValue}
onChange={handleChange}
/>
</div>
);
}
Child2Component:
import React, { useEffect, useState } from "react";
export function Child2Comp({ step, parentState, setParentState }) {
const [inputValue, setInputValue] = useState();
const handleChange = (e) => setInputValue(e.target.value);
useEffect(() => setInputValue(parentState.child2), []);
useEffect(
() =>
setParentState((parentState) => ({
...parentState,
child2: inputValue
})),
[step]
);
return (
<div>
<br />
family:
<input
id="child2"
name="child2"
value={inputValue}
onChange={handleChange}
/>
</div>
);
}
- 在父组件中,我有一个步骤状态来确定应该显示哪个子组件。
- 每个孩子都有自己的状态。
现在我希望当用户通过单击下一步按钮更改步长值时,子状态值保存在父状态中,所以我在每个子状态中使用此代码:
孩子1:
useEffect(
() =>
setParentState((parentState) => ({
...parentState,
child1: inputValue
})),
[step]
);
孩子2:
useEffect(
() =>
setParentState((parentState) => ({
...parentState,
child2: inputValue
})),
[step]
);
但是当父组件中的 step 状态发生变化时,top useEffect 都不会运行。并且子状态不保存在父状态中。:(
你有什么办法解决这个问题吗?
【问题讨论】:
标签: reactjs react-state-management