ReactJS предупреждение: ввод изменяет контролируемый ввод текста типа, чтобы быть неуправляемым - PullRequest
0 голосов
/ 09 сентября 2018

У меня есть форма, которая имеет контролируемые входные данные, и эта форма находится в модальном состоянии с использованием материала-реакции. Все, что я хочу сделать, это заполнить форму, используя доступные данные, чтобы пользователь мог изменять существующие данные. Я использовал решения, упомянутые в других потоках stackoverflow, запрашивающих использовать атрибут Value TextField в этом формате Value = {this.state.name || ''} но у меня не сработало.

    class AddItemModal extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            open: false,
            name: '',
            amount: 0,
            date: moment().format('YYYY-MM-DD'),
            single_transaction: {}
        };
        this.handleChange = this.handleChange.bind(this)
        this.handleClose = this.handleClose.bind(this)
        this.handleSaveChange = this.handleSaveChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this);
        this.input = React.createRef();
    }

    handleChange = name => event => {
        this.setState({
            [name]: event.target.value,
        })
    }

    handleSaveChange() {
        fetch('http://localhost:1337/users/update', {
            method: 'POST',
            headers: {
                "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
            },
            body: 'name=' + this.state.name + '&amount=' + this.state.amount + '&date=' + this.state.date,
        })
            .then((res) => {
                this.setState({ recordAdded: true })
                console.log("Res:", res, this.state.recordAdded);
                fetch('http://localhost:1337/users', {
                    method: 'GET',
                })
                    .then((response) => {
                        console.log(response)
                        return response.json()
                    })
                    .then((transactions) => {
                        this.props.dispatch({
                            type: 'SET_ENTRY',
                            transactions: transactions
                        })
                        this.setState({ recordAdded: false })
                    })
                    .catch(function (error) {
                        console.log('Request failed', error);
                    });
            })
            .catch(function (error) {
                console.log('Request1 failed: ', error);
            });

    }

    handleClose = () => {
        this.props.dispatch({
            type: 'GET_MODAL',
            open: false,
            single_transaction: {}
        });
    }

    handleSubmit(event) {
        alert('A name was submitted: ' + this.input.current.value);
        event.preventDefault();
    }

    render() {
        let { open, single_transaction } = this.props.modal;
        return (
            <div>
                <Dialog
                    open={open}
                    aria-labelledby="alert-dialog-title"
                    aria-describedby="alert-dialog-description"
                    onClose={this.handleClose}>
                    <DialogTitle id="alert-dialog-title">{"Add/Modify Transaction"}</DialogTitle>
                    <DialogContent>
                        <div>
                            <div>
                                <TextField
                                    id="name"
                                    label="Purpose"
                                    type="text"
                                    value={this.state.name}
                                    onChange={this.handleChange('name')}
                                    margin="normal"
                                    autoFocus
                                />
                            </div>
                            <div>
                                <TextField
                                    id="amount"
                                    label="Amount"
                                    type="number"
                                    value={this.state.amount}
                                    onChange={this.handleChange('amount')}
                                    margin="normal"
                                />
                            </div>
                            <div>
                                <TextField
                                    id="date"
                                    label="Date"
                                    type="date"
                                    value={this.state.date}
                                    onChange={this.handleChange('date')}
                                    margin="normal"
                                />
                            </div>
                        </div>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={this.handleSaveChange} variant="contained" color="primary">
                            Save Changes
                        </Button>
                        <Button onClick={this.handleClose} variant="contained" color="secondary">
                            Close
                        </Button>
                    </DialogActions>
                </Dialog>
            </div>
        );
    }
}
...