Reactjs:警告:组件正在更改受控

我正在编写一个 react crud 应用程序,我的 crud 运行良好,但它有一个控制台错误,下面是:


Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: 

我尝试了很多在stackoverflow上阅读太多东西,有人可以帮我吗?


这是我的home.js文件:


import React from "react"

import Table from "./table"

import Form from "./form"


class Home extends React.Component {


    constructor(props) {

        super(props);

        this.state = {

            current: 'SAVE', // button name

            employees: [{name: 'jhon', age: '23', email: 'a@a'}, {name: 'doe', age: '24', email: 'b@a'}],

            currentEmp: {},

            isFormVisible: false

        };

        this.onSubmit = this.onSubmit.bind(this);

        this.onDelete = this.onDelete.bind(this);

        this.setIndex = this.setIndex.bind(this);

    }


    onSubmit(name, age, email, index=null) {

        if(!index && this.state.current == 'SAVE'){

            this.setState({ employees: [...this.state.employees, { name: name, age: age, email: email }] });

        }

        else if(this.state.current == 'Update'){

            var emp = this.state.employees;

            emp[this.state.index].name = name;  //use index from state

            emp[this.state.index].age = age;

            emp[this.state.index].email = email;

            this.setState({

                currentEmp: {},

                employees: emp,

                current: 'SAVE'

            });

        }

        else{

            this.setState({

                currentEmp: {},

                current: 'SAVE',

            });

        }

    };


    setIndex(index){

        var emp = this.state.employees[index];

        emp.index = index;

        this.setState({

            currentEmp: emp,

            current: 'Update',

            index  //set index in state

        });

    }


隔江千里
浏览 336回答 3
3回答

慕森卡

你的问题是这个,currentEmp: {}您正在设置currentEmp为空白对象,并且在Form组件中使用此对象在 中设置状态componentDidUpdate,Form组件中的结果状态未获取值。也不要直接改变状态。您可以将您的currentEmp值对象设置为空,并且您的状态更新应该是,this.setState({   employees: this.state.employees.map((emp,index) => index === this.state.index ? {name,age,email} : emp),   current: 'SAVE',   currentEmp:{name:'',age:'',email:''}});同样在您的Form组件中,在submit您正在执行此操作的功能中,this.setState({name: '', age: '', email: ''});设置时不需要currentEmp:{name:'',age:'',email:''}。你的componentDidUpdate方法会解决这个问题。

哆啦的时光机

您是否尝试过读取submit函数中的属性?喜欢:submit() {    const { name, age, email  } = this.state;    if (this.props.submitMe) {        this.props.submitMe(name, age, email);    }    this.setState({name: '', age: '', email: ''}); // clear form after click on submit}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript