How to redirect after success from ajax call using React-router-component?

只愿长相守 提交于 2019-12-03 12:23:49
kulesa

You need to use the transitionTo function from the Navigation mixin: http://git.io/NmYH. It would be something like this:

// I don't know implementation details of the store,
// but let's assume it has `login` function that fetches
// user id from backend and then calls a callback with 
// this received id
var Store = require('my_store');
var Router = require('react-router');

var MyComponent = React.createClass({
  mixins: [Router.Navigation],

  onClick: function() {
    var self = this;
    Store.login(function(userId){
      self.transitionTo('dashboard', {id: userId});
    });
  },

  render: function() {
    return: <button onClick={this.onClick}>Get user id</button>;
  }
});

It worked for me when I added to the react element properties a require for the router and used the router like this:

// this is the redirect
    this.context.router.push('/search');

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

This should work

var Store = require('Store');
var Navigatable = require('react-router-component').NavigatableMixin

var LoginComponent = React.createClass({
    mixins: [ Navigatable ],

    onClick: function() {
        Store.login(function(userId){
            this.navigate('/user/' + userId)
        }.bind(this));
    },

    render: function() {
        return <button onClick={this.onClick}>Login</button>;
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!