reactjs - 使用 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
解决方案
你忘记{
}
解释
您将从中的props
对象中的父级获取道具
const Child2 = (props) => {...}
您可以使用任何父道具访问它props.*
,也可以使用解构方法
const Child2 = ({username,password}) => {...}
推荐阅读
- android - 键盘上推显示
- python - 将所有关键字仅参数传递给其他函数
- android - 如何在 RecyclerView 适配器列表 Kotlin 中的适配器内实现警报对话框?
- java - BoxCars Java 程序 - 初学者。奇怪的问题:程序不在控制台中运行,但它在 Eclipse Java 中没有列出任何错误
- html - 添加html时div向下移动
- java - Java Swing - ScheduledExecutor 服务停止在用户输入上工作
- content-security-policy - 内容安全策略:页面的设置阻止了资源的加载 data:image/svg+xml;base64,PHN2ZyB3aWR0aD... (“default-src”)
- macos - AppleScript 消息格式 - 新换行符完全失败
- swift - 为什么我得到:“无法转换 '[String] 类型的值?' 到预期的参数类型“字符串?”
- jmeter - 从 jmeter 启动 aws cli 命令