我正在尝试使用 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] 删除。
我来说两句