Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 views
in Technique[技术] by (71.8m points)

javascript - 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.

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

Project Link : 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

How can I achieve this?

question from:https://stackoverflow.com/questions/65829823/how-to-get-updated-props-in-other-components-which-are-in-other-routes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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. 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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...