简体   繁体   English

React 组件道具中的回调 - 正确的触发方式

[英]Callback in props of React component - correct way to fire

Suppose I have a component which is like假设我有一个组件,就像

function Child(props: { onSelect: () => void }) {
    ...
    useEffect(() => {
        // want to fire onSelect here
    }, [...]);
    ...
}

Since props.onSelect might change every render (eg arrow function), I can't add it to the dependency list of useEffect and call it directly.由于 props.onSelect 可能会更改每个渲染(例如箭头函数),因此我无法将其添加到 useEffect 的依赖项列表中并直接调用它。 I used a reducer instead:我改用减速器:

const [, dispatch] = useReducer((state: undefined, action: T) => {
    props.onSelect(action);
    return undefined;
}, undefined);

useEffect(() => { 
    dispatch(...);
}, [...]);

But now I get the error "Warning: Cannot update a component ( Parent ) while rendering a different component ( Child )."但是现在我收到错误“警告:在渲染不同的组件( Child )时无法更新组件( Parent )。”

What's the correct way to fire the parent's onSelect inside some useEffect?在某些useEffect中触发父母的onSelect的正确方法是什么?

You mention你提到

Since props.onSelect might change every render ( eg arrow function ), I can't add it to the dependency list of useEffect and call it directly由于props.onSelect可能会更改每个渲染(例如箭头 function ),我无法将其添加到useEffect的依赖项列表中并直接调用它

You can, but you should make sure that it does not change if there is no reason.你可以,但你应该确保它在没有理由的情况下不会改变。

You should use a useCallback for it on the parent component, so that it remains the same.您应该在父组件上为它使用 useCallback,以便它保持不变。

function Parent (){
...
   const onSelect = useCallback(() => {
     // set local state here
   }, []);
...

return ... <Child onSelect={onSelect} />
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM