【问题标题】:Navigate to other page with props in React JS在 React JS 中使用 props 导航到其他页面
【发布时间】:2020-11-10 15:13:06
【问题描述】:

我想从一个页面重定向到另一个页面并传递道具。但我不希望这些参数在 url 中。

方法:

   saveForLater(){
    if (typeof window !== "undefined") {
      window.location.href = "./DataDisplay/";
    }
  };

我检查了 urlparams 我们可以在 url 中设置 {"id":content}。但我不希望在 url 中传递数据。

我不能在方法中使用 Link/Route。有什么方法可以做/任何图书馆结帐吗?请建议

代码示例:

import React, { Component } from "react";
class DATAFETCH extends Component {
  constructor(props) {
    super(props);
    this.state = {
             Attachments: [],
             validated: false,
             isDoctor:false,
    }

saveForLater(){
    if (typeof window !== "undefined") {
      window.location.href = "./DataDisplay/";
    }
  };

  render() {
    return (

              /////// Various Fields

      <Button
       onClick={() => props.submit()}
       >
)}

【问题讨论】:

  • 您的应用使用什么导航/路由? LinkRoute 是什么,为什么不能使用它们?
  • LINK : import { Link } from "react-router-dom"; ROUTE:从“react-router-dom”导入 { Switch, Route, Redirect };这些不能在用户定义的函数/componentDidMount 函数等方法中使用。我们根据不同的场景使用多种类型的路由。喜欢:onclick/onsubmit 将使用 Link 进行方法遍历,使用 window.location.href 进行页面遍历。

标签: reactjs href


【解决方案1】:

也许您可以使用像API Context 这样的商店经理。 或者像 MobX 或 Redux 这样的替代方案。

【讨论】:

    【解决方案2】:

    我认为您还没有完全理解 react 的工作原理。 LinkRoute 都是组件,因此它们只能在基于类的组件的 render 生命周期函数或 return 中使用和呈现的一个功能组件。除此之外,导航到其他路由的模式是使用 history 对象推送到另一个路由/路径。

    history.push('/DataDisplay');
    

    如果你需要在路由推送的同时发送无关的数据,你可以使用路由状态。

    history.push({
      pathname: '/DataDisplay',
      state: {
        // any values/objects/etc you want to also send to pushed route/path
      },
    });
    

    通过route-propslocation 对象访问路由状态。

    const { /* values/objects/etc */ } = props.location.state;
    

    路由道具只能通过Route直接渲染的组件访问,或者使用withRouter高阶组件或在功能组件的情况下使用react hooks

    您的示例代码

    import React, { Component } from "react";
    import { withRouter } from 'react-router-dom'; // <-- import withRouter HOC
    
    class DATAFETCH extends Component {
      ...
    
      saveForLater(){
        history.push({
          pathname: '/DataDisplay',
          state: {
            id: content // <-- pass in content to key `id`
          },
        });
      };
    
      render() {
        ...
      }
    }
    
    export default withRouter(DATAFETCH); // <-- decorate with withRouter HOC
    

    访问结果路由的组件

    props.location.state.id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-17
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 2019-06-20
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多