提交表单后,React Redirect不会重定向

时间:2020-04-24 01:40:12

标签: reactjs react-router

我尝试了几种方法来使我的应用程序在提交表单后重定向,但是除了使用window.location强制它之外,似乎没有任何作用。目的是让用户填写一个表单,然后在提交后将其重定向到位于“ /”的主页。

现在,我将重定向状态设置为false,并在我的axios帖子提交到提交处理程序之后将其更改,但是它没有任何作用。这是我的组件的样子:

lass Add extends Component {

    constructor(props){
        super(props)
        this.state = {      
        id: "",
        customer: "",
        destination: "",
        driver: "",
        deliveryDate: new Date(),
        redirect: false
        } 
        this.handleChange = this.handleChange.bind(this);
    }


    handleChange(event){
        this.setState({[event.target.name]: event.target.value})
        console.log(this.state)
    }

    onChange = deliveryDate => 
    this.setState({ deliveryDate })


    submitHandler = e => {

        var load = this.state
        load = JSON.stringify(load)
        axios.post('http://localhost:8080/add', load, { headers: {  "Content-Type": "application/json"  }})
        .then(() => this.setState({ redirect: true }))


    }

    render() {
        const { customer, destination, driver, deliveryDate, redirect} = this.state

        return redirect ? <Redirect to='/' /> :

剩下的就是用户填写的用于添加数据的表格。数据正在传递到API,所以我知道POST方法正在工作,但是我不确定问题是什么。

0 个答案:

没有答案