提交表格后改变路线与打字稿反应

时间:2017-07-05 05:20:40

标签: reactjs typescript asynchronous

我是新人的反应。我写的反应与打字稿没有redux。 在我的示例项目中,我想在提交表单后,改变路线,但我不能这样做。以下代码是我的尝试。如何在fetch中更改路由然后功能?为什么这个值未定义!

import * as React from 'react';
import 'isomorphic-fetch';
import { ReactRouter } from 'react-router-dom';

export interface Props {router?: ReactRouter.History.History;}

interface State {name: string;}

export class CreateItem extends React.Component<Props, State> {

    private input: HTMLInputElement;

    constructor(props: Props) {

        super(props);

        this.state = {name: ""};

        this.input = null;
    }

    public render(){

        return <form onSubmit={this.handleSubmit} className="form-horizontal">
            <div className="form-group">
                <label className="col-sm-2 control-label">Date</label>
                <div className="col-sm-5">
                    <input name="name" type="text" value={this.state.name} onChange={this.handleInputChange} className="form-control">
                    </input>
                </div>
            </div>

            <div className="form-group">
                <div className="col-sm-offset-2 col-sm-5">
                    <button type="submit" className="btn btn-default" disabled={!this.state.name}>ADD</button>
                </div>
            </div>
        </form>;
    }

    private handleSubmit = (event: React.FormEvent<HTMLFormElement>): void => {

        event.preventDefault();

        if (this.state.name) {

            var form = new FormData();

            form.append('name', name);

            fetch('/api/SampleData/', { method: 'POST', body: form })
                .then(function (res) {
                    this.props.history.push('/fetchdata');// **this code not work**
                });

            this.setState({
                name: ""
            });
        }
    }

    private handleInputChange = (event: React.FormEvent<HTMLInputElement>): void => {

        const target = event.target;
        const name = target["name"];

        this.setState({
            [name]: (event as any).target.value
        })
    }
}

2 个答案:

答案 0 :(得分:0)

可能迟到了,但无论如何。尝试使用箭头功能来获得正确的 VALUE ID H ---------- ---------- ---------- 1 32 0 54 1 3.5 178 2

np.array =[[  1.00000000e+01  -4.65000000e+02]
           [  1.78319153e+01  -4.60252579e+02]
          ...]

答案 1 :(得分:0)

您使用了错误的React Router。在这里,如何使用它。

样式来自MaterialUI。

const styles = (theme: Theme) =>
  createStyles
  ({})

interface IState
{}

interface IProps
{}

class Home extends React.Component<IProps & WithStyles<typeof styles> & RouteComponentProps<{}>, IState>
{   
    constructor(props: IProps & WithStyles<typeof styles> & RouteComponentProps<{}>)
    {
        super(props);

        this.state =
        {
        }
    }
}

导航使用:this.props.history.push(your route goes here);