所以我正在通过电子书学习react js,并坚持使用它,
我一直收到错误:"无法读取未定义的属性‘push’。">
我的App.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { HashRouter as Router, Route, Switch, Redirect, withRouter } from 'react-router-dom';
import IssueList from './IssueList.jsx';
import IssueEdit from './IssueEdit.jsx';
const contentNode = document.getElementById('contents');
const NoMatch = () =><p>Page Not Found</p>;
const RoutedApp = () => (
<Router>
<Switch>
<Route exact path="/" render={ () => <Redirect to="/issues" /> } />
<Route exact path="/issues" component={withRouter(IssueList)} />
<Route path="/issues/:id" component={IssueEdit} />
<Route path="*" component={NoMatch} />
</Switch>
</Router>
);
ReactDOM.render(<RoutedApp />, contentNode);
if(module.hot){
module.hot.accept();
}
IssueList.jsx
...
import React from 'react';
import QueryString from 'query-string';
import 'whatwg-fetch';
import { Link } from 'react-router-dom';
...
export default class IssueList extends React.Component{
constructor(props){
super(props);
this.state = { issues: [] };
this.createIssue = this.createIssue.bind(this);
this.setFilter = this.setFilter.bind(this);
}
setFilter(query){
this.props.router.push({ pathname: this.props.location.pathname, query });
}
}
有人能告诉我它怎么了吗?
您应该将组件封装在react router中,以访问历史属性。所以你的IssueList.jsx
应该是这样的:
...
import React from 'react';
import QueryString from 'query-string';
import 'whatwg-fetch';
import { withRouter } from 'react-router'
import { Link } from 'react-router-dom';
...
class IssueList extends React.Component{
constructor(props){
super(props);
this.state = { issues: [] };
this.createIssue = this.createIssue.bind(this);
this.setFilter = this.setFilter.bind(this);
}
setFilter(query){
this.props.history.push({ pathname: this.props.location.pathname, query });
}
}
export default withRouter(IssueList)
多亏了这篇文章,它终于开始工作了:如何在react router中以编程方式更新查询参数?
...
import React from 'react';
import QueryString from 'query-string';
import 'whatwg-fetch';
import { Link } from 'react-router-dom';
...
export default class IssueList extends React.Component{
constructor(props){
super(props);
this.state = { issues: [] };
this.createIssue = this.createIssue.bind(this);
this.setFilter = this.setFilter.bind(this);
}
setFilter(query){
this.props.history.push({
pathname: this.props.location.pathname,
search: '?' + QueryString.stringify(query)
});
}
}