在表单提交上调用`componentDidUpdate`

时间:2018-05-25 23:12:18

标签: javascript reactjs react-lifecycle

我有一个类组件如下:

class App extends Component {
    constructor(props){
        super(props);
        this.state = {
            abc: '',
            someQuery: ''
        }
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleChange = this.handleChange.bind(this);
    }

    componentDidUpdate(){
        fetch(`/someLink/${this.state.abc}`)
        .then(response => {
            return response.json();
        }).then(data => {
            this.setState({
                someQuery: data.xxx
            });
        });
    }
    handleSubmit(e){
        const target = e.target;
        const value = target.value;

        this.setState({
            abc: value
        })
        e.preventDefault();
    };
    handleChange(e){
        const target = e.target;
        const value = target.value;

        this.setState({
            abc: value
        });
    };
    render(){
        return(
            <form onSubmit={this.handleSubmit}>
                <input name='abc' value={this.state.abc} onChange={this.handleChange} />
                <input type="submit" value="Submit" />
            </form>

            <div>{this.state.abc} is currently accessing data from {this.state.someQuery}</div>
        )
    }
}

每次更新输入字段的值并单击“提交”按钮时,如何运行componentDidUpdate()

上面调用了生命周期,但由于setState内的handleChange(),生命周期也会在我输入内容时被调用,并且不会等到提交按钮是点击。

setState中删除handleChange()会使输入字段值不再可编辑(输入字段上无法输入)。

我需要在生命周期中附加到api link的输入字段值,但我似乎无法找到正确的方法来执行此操作。

1 个答案:

答案 0 :(得分:3)

您可以在组件类中添加任何方法,并在提交时调用它。 componentDidUpdate不适合做这样的事情,特别是设置状态是犯罪:D

class App extends Component {
    constructor(props){
        super(props);
        this.state = {
            abc: '',
            someQuery: ''
        }
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleChange = this.handleChange.bind(this);
    }

    doSommething (value){
        fetch(`/someLink/${value}`)
        .then(response => {
            return response.json();
        }).then(data => {
            this.setState({
                someQuery: data.xxx
            });
        });
    }
    handleSubmit(e){
        const target = e.target;
        const value = target.value;

        this.setState({
            abc: value
        })
        e.preventDefault();
        doSommething(value);
    };
    handleChange(e){
        const target = e.target;
        const value = target.value;

        this.setState({
            abc: value
        });
    };
    render(){
        return(
            <form onSubmit={this.handleSubmit}>
                <input name='abc' value={this.state.abc} onChange={this.handleChange} />
                <input type="submit" value="Submit" />
            </form>

            <div>{this.state.abc} is currently accessing data from {this.state.someQuery}</div>
        )
    }
}