2

我有一个类组件如下:

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()每次更新输入字段的值并单击提交按钮时如何运行?

上面调用了生命周期,但由于其中的原因setStatehandleChange()生命周期在我输入内容的那一刻被调用,而不是等到单击提交按钮。

删除setStatefromhandleChange()会使输入字段值不再可编辑(无法在输入字段上键入)。

我需要api link在生命周期中附加输入字段值,但我似乎无法找出正确的方法来做到这一点。

4

1 回答 1

4

您可以在组件类中添加任何方法并在提交时调用它。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>
        )
    }
}

于 2018-05-25T23:22:23.403 回答