我在功能组件中实现一个组件,其中有其他几个子组件,它们相互传递数据。我需要将数据从父组件传递到子组件,并在那里调用一些函数来使用它。在类组件集中,我们使用componentdidupdate,但无法理解如何在功能组件中进行操作。
一个想法是使用useEffect钩子,但无法使用它。
发布于 2021-02-05 12:58:37
我将在这里尝试一下,因为我们没有上下文或代码可供使用。
useEffect接受依赖数组,当值或对象引用发生更改时,它将对该数组作出反应。
const ChildComponent = (props) => {
const {
valuePassedFromParent
} = props;
const actionFunction = (value) => {
//perform some tasks with value passed from parent when it changes
}
//this is similar to componentDidUpdate, but it reacts to changes in valuePassedFromParent though props since its in the useEffect dependency array
useEffect(() => {
//do something with valuePassedFromParent
actionFunction(valuePassedFromParent);
},[valuePassedFromParent]);
return (
<div>
</div>
)
}发布于 2021-02-05 12:56:58
您可以使用useEffect复制componentdidupdate的行为,如下所示:
const [myState,setMyState] = useState();
useEffect(() => {
...
},[myState]);函数使用效果将在每次更新myState时运行,就像componentdiduptate所做的那样。
在您的示例中,如果我理解得很好,则由父组件给出状态,所以只需将数组依赖项中的myState替换为通过子组件的支柱提供的状态。
https://stackoverflow.com/questions/66063632
复制相似问题