【问题标题】:React router shows up as undefined, how would I re-route to a certain page without using window.locationReact路由器显示为未定义,我如何在不使用window.location的情况下重新路由到某个页面
【发布时间】:2016-06-18 15:16:07
【问题描述】:

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;

使用 window.location 时的重定向仅在某些时候有效,并且不是您应该在反应中做事的一般方式,当我尝试要求路由器时,由于某种原因它总是显示为未定义。我不确定为什么我不能要求它,我在其他地方看到我可能会使用导航混合,但我仍然不确定。任何帮助将不胜感激。

【问题讨论】:

    标签: redirect reactjs routing


    【解决方案1】:

    使用这个:

    // 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      • 2018-02-16
      • 2021-07-18
      • 2021-10-09
      • 1970-01-01
      相关资源
      最近更新 更多