如何使用路由器从一个组件访问传递的数据到另一个 ReactJS

How to access passed data using router from one component to another ReactJS

//import routes from "./routes";
import { Link, withRouter, NavLink, useHistory } from "react-router-dom";

export default function App() {
  console.log(this.props.data.data);
  const [value1, setValue1] = useState(0);
  const [value2, setValue2] = useState(0);
...}

slider.js中的这部分代码访问从上一页传递的数据变量,如下所述

        axios
        .post(
          "/get_spec_other",
          {
            selected_country: this.props.selectedCountry,
            selected_disease: this.props.selectedDisease,
            selected_drug: this.props.selectedDrugs,
          },
          { headers: { "content-type": "application/json" } }
        )
        .then((res) => {
          const SpecificationName = Array.from(res.data);
          console.log(res.data);
          this.props.history.push({pathname: '/slider', data: res.data});

          alert(res.data);

这是我将数据传递到 /slider 并打开 slider.js 的地方。

问题是您正在使用功能组件并期望“this”在那里。 它应该是这样的:(注意在 App 的函数参数中声明的道具)

//import routes from "./routes";
import { Link, withRouter, NavLink, useHistory } from "react-router-dom";

export default function App(props) {
  console.log(props.data.data);
  const [value1, setValue1] = useState(0);
  const [value2, setValue2] = useState(0);
...}

您需要做的另一件事是检查您是否使用了正确的挂钩来获取数据: https://css-tricks.com/the-hooks-of-react-router/

谢谢!我意识到我哪里出错了,我没有将数据从父组件传递到子组件

render() {     
const { data } = this.props.location     
console.log(data); ...
} 

return ( 
....  
<App data={data}/> 
...
} 

export default function App(data) {   
//const { data } = props.location   
console.log(data); 
......
}