简体   繁体   English

如何在其他路线中的其他组件中获取更新的道具?

[英]how to get updated props in other components which are in other routes?

I have a react project.我有一个反应项目。 I have 3 routes, which are /, /adult, /children.我有 3 条路线,分别是 /、/adult、/children。

I have created the states and onChange handlers in App.js files and passing them as props to the sub components and updating the value in one of the sub component but the updated value not showing in the other child component我在 App.js 文件中创建了状态和 onChange 处理程序,并将它们作为道具传递给子组件,并更新了其中一个子组件中的值,但更新后的值未显示在另一个子组件中

Project Link: https://codesandbox.io/s/trusting-haslett-pz2by?file=/src项目链接: https://codesandbox.io/s/trusting-haslett-pz2by?file=/src

When I am incrementing adult value, its updating in /adult page, but I have opened /children route in another tab but the props value isn't getting updated there当我增加成人值时,它会在 /adult 页面中更新,但我在另一个选项卡中打开了 /children 路线,但道具值没有在那里更新

How can I achieve this?我怎样才能做到这一点?

If you're running the same page in two different browser tabs, these are completely unrelated.如果您在两个不同的浏览器选项卡中运行同一页面,则它们完全不相关。 Each has its own memory, and executes its own javascript, and one cannot affect the other, unless you involve a server or websockets.每个都有自己的 memory,并执行自己的 javascript,一个不能影响另一个,除非你涉及服务器或 websockets。

Your current code works fine, as long as you stay in the same tab.只要您留在同一个选项卡中,您当前的代码就可以正常工作。 Your state is in the App component and will be available to both the adults route and the child route.您的 state 位于 App 组件中,可用于成人路线和儿童路线。 To test this, try adding a link from your adult page to your children page.要对此进行测试,请尝试将您的成人页面的链接添加到您的儿童页面。 You can increment a few times on the adult page, then link to the children page and see the same value您可以在成人页面上增加几次,然后链接到子页面并查看相同的值

import React from "react";
import { Link } from "react-router-dom";
const Adult = (props) => {
  return (
    <div>
      <button onClick={props.incAdult}>Increment</button>
      <p> No of Adults : {props.adults} </p>
      <Link to="/children">Test</Link>
    </div>
  );
};
export default Adult;

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

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