简体   繁体   English

React Router显示为未定义,我如何不使用window.location重新路由到某个页面

[英]React router shows up as undefined, how would I re-route to a certain page without using window.location

 var React = require('react'); var PropTypes = React.PropTypes; var SearchStore = require('../stores/SearchStore.js'); var Router = require('react-router'); var SearchResults = React.createClass({ getInitialState: function() { return( {searchResults: SearchStore.all()}); }, componentDidMount: function() { this.searchResultsToken = SearchStore.addListener(this.newSearchResults); }, componentWillUnmount: function() { this.searchResultsToken.remove(); }, newSearchResults: function() { this.setState({searchResults: SearchStore.all()}); }, userDirect: function(id){ window.location = '/#/user/' + id }, songDirect: function(id){ window.location = '/#/songs/' + id }, playlistDirect: function(id){ window.location = '/#/playlists/' + id }, createSearchResults: function() { return this.state.searchResults.map(function(result, idx){ if (result.username !== undefined){ return <li key={idx} onClick={this.userDirect.bind(null, result.id)}>{result.username}</li>; }else if (result.genre !== undefined){ return <li key={idx} onClick={this.songDirect.bind(null, result.id)} >{result.title}</li>; }else{ return <li key={idx} onClick={this.playlistDirect.bind(null, result.id)} >{result.title}</li>; } }.bind(this)); }, render: function() { debugger; return ( <ul id='search-results'> {this.createSearchResults()} </ul> ); } }); module.exports = SearchResults; 

The redirects when using window.location only work some of the time and aren't the general way you're supposed to do things in react, when I try to require the router it always shows up as undefined for some reason. 使用window.location时,重定向仅在某些时间有效,并且不是您应做的一般反应方式,当我尝试要求路由器时,出于某种原因它总是显示为未定义。 I'm not sure why i cant require it, I saw somewhere else I would likely use a navigation mixin, but I'm still unsure. 我不确定为什么我不能要求它,我在其他地方看到了我可能会使用导航混合功能,但是我仍然不确定。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Use this: 用这个:

// this is the redirect. Use it whereever you want
  this.context.router.push('/search');

// this should appear outside the element
    SearchResults.contextTypes = {
         router: React.PropTypes.object.isRequired
     };
     module.exports = SearchResults;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM