React在重定向后没有做任何事情

问题描述 投票:-1回答:1

我点击它有一个NavLink它会激活一个函数,它将它重定向到另一个页面但是在重定向时它不会执行任何任务,如console.log(“Hi”);

 <NavLink to="/data" onClick={this.performTask} exact ={

重定向后如何执行这些功能?

performTask(event) {

    //browserHistory.push("/data/"+this.state.category1+'/'+this.state.zip1+'/'+this.state.age1+'/'+'/'+this.state.gender1);
    console.log(this);
    console.log(this.state.zip1);
    console.log(this.state.age1);
    console.log("asd");
    console.log(window.location.href);
    fetch('/api/customers/'+this.state.category1+'/'+this.state.zip1+'/'+this.state.age1+'/'+'/'+this.state.gender1)
        .then(res => res.json())
        .then(customers => this.setState({customers}, () => console.log('Customers fetched...', customers)));
    event.preventDefault();
}
reactjs redirect
1个回答
0
投票

您无法重定向,然后在同一组件中执行某些操作。

一些解决方法:

执行操作后重定向

将performTask更改为:

performTask(event) {
    event.preventDefault(); // prevent first
    console.log(this);
    console.log(this.state.zip1);
    console.log(this.state.age1);
    console.log("asd");
    console.log(window.location.href);
    fetch('/api/customers/'+this.state.category1+'/'+this.state.zip1+'/'+this.state.age1+'/'+'/'+this.state.gender1)
        .then(res => res.json())
        .then(customers => this.setState({customers}, () => console.log('Customers fetched...', customers)));
    // redirect 
    browserHistory.push("/data/" + this.state.category1 +'/' + this.state.zip1 + '/' + this.state.age1 + '/'+'/' + this.state.gender1);
}

如果上一个任务是异步的,你必须等待:

async performTask(event) {
    await doAsync();
    // redirect 
    browserHistory.push("/data/" + this.state.category1 +'/' + this.state.zip1 + '/' + this.state.age1 + '/'+'/' + this.state.gender1); 
}

重定向和管理重定向组件中的操作

如果重定向到给定路由,则在该路由路由到的组件中,根据组件是否已安装,更改componentDidMount或componentWillReceiveProps函数。

performTask(event) {
    event.preventDefault(); // prevent first
    fetch('/api/customers/' + this.state.category1 + '/' + this.state.zip1 + '/' + this.state.age1+'/' + '/' + this.state.gender1)
            .then(res => res.json())
            .then(customers => this.setState({customers}, () => console.log('Customers fetched...', customers)));
    browserHistory.push("/data/" + this.state.category1 +'/' + this.state.zip1 + '/' + this.state.age1 + '/'+'/' + this.state.gender1);
}

在您的RedirectedComponent中:

class RedirectedComponent extends Component {
...
componentDidMount() {
    this.performTasks();
}

componentWillReceiveProps(prevProps) {
    this.performTasks();
}

performTasks(){
    // do things
    console.log('Hi');
}
© www.soinside.com 2019 - 2024. All rights reserved.