反应路由器重定向条件

时间:2017-08-21 21:40:26

标签: reactjs react-router conditional

我尝试制作一个按钮,只在正确完成验证后才将用户重定向到新页面。

有没有办法做这样的事情? 如何在类方法中激活Route?

void Main()
{
    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
    var connectionSettings = new ConnectionSettings(pool)
        .InferMappingFor<Account>(m => m.IndexName("bank").TypeName("account"))
        .DefaultIndex("default-index");

    var client = new ElasticClient(connectionSettings);

    // query input to controller action
    var query = new
    {
        query = new { match_all = new { } },
        sort = new [] { new { account_number = "asc" } }
    };

    var index = client.Infer.IndexName(IndexName.From<Account>());
    var type = client.Infer.TypeName(TypeName.From<Account>());

    SearchResponse<Account> response = 
        client.LowLevel.Search<SearchResponse<Account>>(index, type, query).Body;
}

public class Account
{
}

3 个答案:

答案 0 :(得分:1)

Purgatory表示你可以在不使用<Redirect />的情况下执行此操作,但是否则你可以使你的组件成为有状态组件,然后像这样进行条件渲染

render() {
    !this.state.redirect ? 
      <button onClick={this.saveAndContinue}>Save and Continue</button> :
      <Redirect to='/other_tab'>
  }

saveAndContinue()更改组件状态。

saveAndContinue () {
    var valid = validator.validate(this.props.form)
    if (valid) {
      axios.post('/path')
      this.setState({redirect: true});
    } else {
      validator.showErrors()
    }
  }

当状态改变时,它将导致重新渲染,这次将呈现<Redirect />

注意:我实际上并未运行此代码段,因此可能包含(希望是次要的)错误。

答案 1 :(得分:1)

正如所讨论的那样,您应该可以history通过this.props.history访问push对象。

如果您查看// Use push, replace, and go to navigate around. this.props.history.push('/home', { some: 'state' }) 功能,这会将您重定向到您需要的任何路线。 例如:

on run argv
  set theQuery to item 1 of argv
    set theSubject to date string of (current date) & " Call Follow up"
    tell application "Mail"
    activate
    make new outgoing message with properties {subject:theSubject, content:theQuery & return & return}
end tell
end run

here

答案 2 :(得分:0)

我今天需要这样做。 这是我的代码,请记住,我决定将其设置为HOC,您可以选择包装还是不包装。 对于具有多个重定向案例的用例,您肯定要使用此内联而不是包装。

import React from 'react';
import {Redirect} from 'react-router';

interface IConditionalRedirectProps {
    shouldRedirect: boolean,
    to: string
}

export const ConditionalRedirect: React.FC<IConditionalRedirectProps> = (props) => {
    const {shouldRedirect, to, children} = props;

    if (shouldRedirect) {
        console.log('redirecting');
        return <Redirect to={to}/>
    } else {
        return (
            <>
                {children}
            </>
        )
    }
};

用法:

<ConditionalRedirect shouldRedirect={isButtonClicked()}
                             to={'some url'}>
    <Normal Elements here>
</ConditionalRedirect>