【问题标题】:Forcing reevaluation of child component强制重新评估子组件
【发布时间】:2021-08-17 09:14:12
【问题描述】:

我有一个使用自定义 <Input> 元素的表单。在Input 组件中,我管理输入的状态(有效/无效)。在表单中,我要求用户重新输入密码,我希望如果用户正确输入两个密码然后修改第一个密码,第二个密码将变为无效(获得红色背景色)。

所以在Form 组件中,我想在每次第一个密码的值更改时触发对第二个密码Input 的重新评估。

Form 中,我将第一个密码的值存储在useReducer 状态中,我认为在组件的props 中传递它会自动触发重新评估,但事实并非如此。

Password
[*****_____]

Re-enter Password
[*****_____]  // "valid" because it has the same value of the first password



...then the user modify the first password:

Password
[********__]

Re-enter Password
[*****_____]  // this component should be reevaluated and set itself to "invalid"

我这里把第二个组件的props中的第一个密码的值传进去了:

<Input
    ...props...
    testingFunction={password => password && password === formState.password.value}
/>

我还尝试通过添加此属性更明确地传递值:dependencies={formState.password.value},但它也不起作用。

那么这种方法有什么问题,什么是强制重新评估第二个密码组件的好方法?

【问题讨论】:

    标签: reactjs next.js react-props react-functional-component


    【解决方案1】:

    您可以使用useEffect 在您的Input 组件中运行您的re-evaluation

    例如

    import React, { useEffect } from "react";
    
    interface IInputProps extends HTMLInputElement {
      reevaluate?: string;
    }
    
    const Input: React.FC<IInputProps> = (props: IInputProps) => {
      useEffect(() => {
        console.log("Run your evaluation code here - This code block will be run whenever `reevaluate` prop is changed");
      }, [props.reevaluate])
    
      return (
        <input type="text" />
      );
    };
    

    【讨论】:

    • 你是在告诉我,组件默认情况下会看到它的 props 发生变化并且不会在乎,但是你可以通过组件内部的 useEffect 使 props 触发动作?
    • 我试过了,效果很好!非常感谢!
    • @SheikYerbouti 回答你的第一个问题 - 是的,在初始渲染后它并没有在乎。当状态改变(不是道具)时执行重新渲染 - 但是,如果您将父母的状态传递给孩子的道具,一开始很难判断,因为重新渲染的是父母。
    • 是的,没错,父组件正在重新渲染。那么不应该重新渲染子组件,至少在它的道具发生变化之后?我认为在 React 中你需要使用 useCallback 和 React.memo() 来防止孩子重新评估。所以我怀疑我的问题是由于Next.js自动优化代码
    • @SheikYerbouti 当父母重新渲染时,孩子也应该这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 2020-10-14
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多