reactjs - 在React-Hooks UseRef中我无法获取新的状态值

标签 reactjs typescript ecmascript-6 react-hooks react-ref

我正在尝试使用react-hooks使用useref,但是当我调用setAccountVal方法时,尽管当我提醒值时子项的状态发生了变化,但它仍然是“Ege”。您对这个案例有什么了解吗?

    import React, { useState, useRef, useImperativeHandle, useEffect, forwardRef } from "react";
interface A {
    name?: string;
}

const Child = forwardRef((props: A, ref) => {
    const [acc, setAcc] = useState("Ege");
    useImperativeHandle(ref, () => ({
        getAlert(value: string) {
            alert("getAlert from Child===>" + value);
        },

        setAccountVal(val: string) {
            setAcc(val);

        },
        acc
    }));

    useEffect(
        () => {
            debugger;
            setAcc(props.name || "dummy");
            console.log(acc + " --");
        },
        [props.name]
    );

const changeState = (e:React.FormEvent<HTMLInputElement>)=>{
    setAcc(e.currentTarget.value);
}


    return <input onChange={changeState}></input>;
})
function App() {
    let [name, setName] = useState("Nate");

    let nameRef = useRef<any>(null);

    const submitButton = () => {
        debugger;
        const comp = nameRef.current;
        comp.setAccountVal("Mahmut");
        comp.getAlert(comp.acc);
    };

    return (
        <div className="App">
            <p>{name}</p>
            <div>
                <button type="button" onClick={submitButton}>
                    Submit
        </button>
                <Child ref={nameRef} />
            </div>
        </div>
    );
}

export default App;

当我调用普通方法时,我可以看到我想要的东西。但问题是我可以在 acc 状态上看到新的状态值,但是当我从父级获取它时,它显示旧的(实际上是初始状态 val(“Ege”))状态值。

Edit : Actually what i want to do is below

//Child component with forwardRef
const [account, setAccount] = useState("defaultAccount");
const [branch, setBranch] = useState("defaultBranch");
const [person, setPerson] = useState("defaultPerson");

useImperativeHandle(ref, () => ({
    selectedAccount: account,
    selectedBranch: branch,
    selectedPerson: person
}));


//Parent component
const childComponentRef = useRef(null);
//Is it possible to change child component's state? Is it allowed?
childComponentRef.current.selectedAccount = "new account";
childComponentRef.current.selectedBranch = "new branch";
childComponentRef.current.selectedPerson = "new person";

alert(childComponentRef.current.selectedAccount);
alert(childComponentRef.current.selectedBranch);
alert(childComponentRef.current.selectedPerson);

//We can change these variables but child component does not rerender with new values.

Ok! I've found the solution. When i use the ref variables with getter setter now i can set also get the current values with useRef!!

//Child component with forwardRef
const [account, setAccount] = useState("defaultAccount");
const [branch, setBranch] = useState("defaultBranch");
const [person, setPerson] = useState("defaultPerson");

useImperativeHandle(ref, () => ({
    **get account(){
     return account;
    },
    set account(val : string){
    setAccount(val);
    },**
    selectedBranch: branch,
    selectedPerson: person
}));


//Parent component
const childComponentRef = useRef(null);
//Is it possible to change child component's state? Is it allowed?
childComponentRef.current.selectedAccount = "new account";
childComponentRef.current.selectedBranch = "new branch";
childComponentRef.current.selectedPerson = "new person";

alert(childComponentRef.current.selectedAccount);
alert(childComponentRef.current.selectedBranch);
alert(childComponentRef.current.selectedPerson);

//We can change these variables but child component does not rerender with new values

详细演示:

Edit React-Ref with Hooks .

最佳答案

这是因为您使用 useImperativeHandle 时没有设置任何输入,因此函数永远不会更新。只需添加 acc 作为输入,它就会起作用:

useImperativeHandle(ref, () => ({
  getAlert(value: string) {
    alert("getAlert from Child===>" + value);
  },

  setAccountVal(val: string) {
    setAcc(val);

  },
  acc
}), [acc]);

关于reactjs - 在React-Hooks UseRef中我无法获取新的状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54665481/

相关文章:

typescript - 检查后表达式___发生了变化

javascript - 出于某种原因不允许我在 Ember js 中导入模块

javascript - 如何通过回调和匿名函数将 'this' 保留在范围内?

javascript - react createElement 不工作返回 [对象对象]

reactjs - 使用react-spring/react-motion进行快照测试

reactjs - ' react -i18next : withNamespaces is not a function' when testing

javascript - TypeScript 关联数组

javascript - 为什么我需要在 componentDidUpdate() 中使用 prevProps 和 prevState ?

javascript - 当可观察到的变化时,mobx 观察者突然不重新渲染

javascript - typescript 导入自