首页 > 解决方案 > 使用 React Hooks 将数据从 Child 传递给其他 Child

问题描述

所以这是将数据传递给其子代的父函数:

function Parent() {

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");


  return (
    <div className="Parent">
      <BrowserRouter>

          <Route exact path="/child1" render={ () =>
             <Child1 setUsername={setUsername} setPassword={setPassword} password={password} username={username}/> 
             />

          <Route exact path="/child2" 
            render={() =>
             <Child2 username={username} password={password}/>
            }/>

        </BrowserRouter>
    </div>
  );
}

export default Parent;

我试图实现的是,Child1将从端点获取数据,并将数据与setPassword()and一起存储,setUsername()并且第一个 Child 将页面重定向到第二个 Child(又名Child2)。

问题是Child2console.log("Username: "+username)在 i或console.log("Password: "+password)i 获取时不会以某种方式获取数据[object Object]

孩子1

export default function Child1({setPassword,setUsername,username,password}) {

  const history = useHistory();

  const handleClick = () => {
   setUsername("myUsername");
   setPassword("myPassword");
   history.push("/child2") 
  }

  return (
    <div>
      Child 1 Page
    <button onClick={handleClick}> A button</button>
    </div>
  );
}

孩子2:

const Child2 = (username,password) => {


    useEffect(() => {
         console.log("Username: "+username);
         console.log("Password: "+password);
    }, [])

    return (
        <div >
           Child 2 Page
        </div>
    )
}

export default Child2

标签: reactjsreact-routerreact-hooks

解决方案


你忘记{ }

解释

您将从中的props对象中的父级获取道具

const Child2 = (props) => {...}

您可以使用任何父道具访问它props.*,也可以使用解构方法

const Child2 = ({username,password}) => {...}

推荐阅读