在 react-router 中使用 history.push() 传递道具时出现问题

kika123

我正在尝试使用 history.push() 将 props 传递给 React 中的另一个组件。我的代码如下所示:

 history.push({pathname:`/tickets/solveticket`,
                state:{ticket:this.props.ticketInfo, user:this.props.currentUser}}); 


 window.location.reload()

历史是这样导出的:

 import { createBrowserHistory } from 'history';

export const history = createBrowserHistory();

和我的路线配置:

 import {BrowserRouter as Router,Route,Switch,Link } from "react-router-dom"; 
    <Router history={history}> 
    ... <PrivateRoute exact path="/" component={Dashboard} />
                    <Route exact path="/login" component={Login} />
                    <Route exact path="/register" component={Register} />


                    <PrivateRoute exact path="/dashboard" component={Dashboard} />  

`

在 /tickets/solveticket url 上呈现的组件采用这样的历史参数:

constructor(props){
    super(props)
    this.state={
       ticketToSolve:this.props.location.state.ticket,
       currentUser:this.props.location.state.user
    }
}

但我收到此错误:

类型错误:无法读取未定义的属性“票”

我试图用 withRouter 包装所有东西,但它仍然不起作用。我还尝试使用 this.props.history.push 而不是导出的历史记录,但在这种情况下,我的历史记录无法识别。请把它写下来..提前谢谢:)

拉詹·拉加

尝试

constructor(props){
    super(props)
    this.state={
       ticketToSolve:"",
       currentUser:""
    }
}
componentDidMount(){
 if(this.props.location.state){
  this.setState({
       ticketToSolve:this.props.location.state.ticket,
       currentUser:this.props.location.state.user
    })
  }
}

因为有时您不能确定变量已经设置。可能是反应先渲染此代码。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在React Router中使用history.push()时需要刷新的问题

使用react-router-dom的history.push

如何使用React的Router v4 history.push()

如何使用Jest通过调用history.push来测试React-Router导航?

使用react-router v4的this.props.history.push打开窗口?

不确定如何使用react-router v4实现history.push

如何使用Jest模拟新的React Router Hooks的history.push

使用react-router的history.push()和自定义URL参数

如何使用 history.push 传递道具

React router history.push 回退到 404 路由

react-router重定向vs history.push

如果使用 history.push 访问特定路由,React-Router v5 不会重定向

导入使用React-Router-Dom的自定义模块组件时出现问题

React / Router / MemoryRouter-如何传递历史记录属性并在子组件中使用push()?

在 React 中使用 find 函数时出现问题

在React中如何使用history.push将对象从组件传递到子组件并读取数据

Redux和React Router:梳理调度和导航(history.push)

在React Router中,如何删除/更改我之前发送的history.push中的参数?

如果react-router4中的位置不变,如何防止history.push?

react-router-dom-链接和history.push之间的区别?

History.Push链接到带有React Router的新选项卡

React Router的useHistory。History.push更改url但不加载组件

React Router history.push() 更改了 url 但未呈現組件內容

使用React-Router在React中使用实例的URL问题

使用AJAX时history.pushState出现问题

React-Routing 使用 history.push() 获取 404 页面

无法使用history.push来异步路由,React JS

如何使用 history.push 在 React 中获取参数

在React中使用react-router时组件消失