【问题标题】:Immutability Issue: Warning: A component is changing a controlled input to be uncontrolled. (Opposite of不变性问题:警告:组件正在将受控输入更改为不受控。 (的反面
【发布时间】:2021-05-13 11:40:05
【问题描述】:

代码:

   class Table extends Component {

    constructor(props)
    {
        super(props);
        this.state = {
            body: Body
        }
    }

    

    onChangeHandler = (event, index) => {

        const value = event.target.value;
        const body = this.state.body;
        body[index] = value;
        this.setState(prevState => ({
            ...prevState,
            body: body
        }))

    }

    render() {

        const heads = Headers.map((element, index) => <th key = {"__trow__" + index}>{element}</th>);
        const body = this.state.body.map((element, index) => <td key = {"__trow_body__" + index}>

            <div className = {classes.EditFieldCell}>
            <input type = {element.inputType} 
                   className = {classes.EditFieldCellInput}
                   value = {element.title}
                   onChange = {(event) => this.onChangeHandler(event, index)}
            >
            </input>
            </div>
            

        </td>
        );


        return <table className = {classes.prettyTable}>
        <thead>
        <tr>
            {
                heads
            }
        </tr>
        </thead>
        <tbody>
        <tr>
            {
                body
            }
        </tr>
        </tbody>
        </table>

    }

}


export default Table;

我尝试通过扩展运算符 this.setState、Object.assign 更新状态,但它们似乎都不起作用。我无法理解我的状态究竟是在什么时候失控的。

在哪里Headers = ["A","B","C"]

正文 = [ {title: "Check 1",inputType: "text"}, {title: "Check 2 B",inputType: "text"},{title: "Check 1",inputType: "text"}]

【问题讨论】:

  • 你在这里改变你的状态:body[index] = value;Never mutate state.
  • 哦,我明白了......那么这里有什么更好的选择?试过:const body = [...this.state.body]; 这给了我同样的警告。

标签: reactjs


【解决方案1】:

某个事件正在将input 的值更改为undefined

input 值应设置为空值('') 而不是undefined

【讨论】:

  • 我没听懂你...我认为这与未定义的输入值无关。它更多的是某种不变性。另外你的建议,我也试过了,但它不起作用,因为输入字段然后变成了常量。
【解决方案2】:

感谢@riven 和@Ravi 的协助。我意识到我正在尝试更新具有两个属性的对象数组:

                   className = {classes.EditFieldCellInput}
                   value = {element.title}

所以我改变了: body[index].title = value; 修复它。

另外一个更复杂的解决方案是:

onChangeHandler = (event, index) => {

        const value = event.target.value;
        const body = [...this.state.body];
        const bodyElement = {...body[index]};

        bodyElement.title = value;
        body[index] = bodyElement;
        this.setState(prevState => ({
            ...prevState,
            body: body
        }))

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2019-06-03
    • 2021-07-29
    • 2023-03-05
    • 1970-01-01
    • 2018-01-13
    • 2018-11-30
    相关资源
    最近更新 更多