【问题标题】:Editdamnpoll is changing an uncontrolled input of type text to be controlledEditdamnpoll 正在更改要控制的文本类型的不受控制的输入
【发布时间】:2017-06-01 03:57:52
【问题描述】:

我收到了这个错误

警告:Editdamnpoll 正在更改文本类型的不受控制的输入 被控制。输入元素不应从不受控制的状态切换 控制(反之亦然)。决定使用受控或 在组件的生命周期内不受控制的输入元素。

这是我的代码

```

import React, { Component } from 'react';

import Api from '../../utils/ApiManager';
import {Link} from 'react-router';

var pollId = 2;
var newVotesObj ={};

class Editdamnpoll extends Component {
    constructor(){
        super()
              this.state = {
                poll:{
                    pollquestion: 'ankur',
                    author: 'ankur',
                    responses: [1]
                },
                newresponses:[2]
        };

    }
    componentWillMount(){
        var urlWithId =this.props.location.pathname;
        var pollID = urlWithId.split('/').pop();
        console.log("here's the poll id",pollID)
        Api.get('/api/polls/' + pollID, null, (err, response) => {
            if(err){
                 alert("Error: " + err); 

            }
            else{

                var newobj = {pollquestion:response.message.pollquestion,author:response.message.author,responses:response.message.responses}
                this.setState({
                    poll:newobj

                });
                var newarr = this.state.poll.responses.map(function(i,index){
                    return i.response
                })
                var tochange = this.state.newresponses;
                this.setState({
                    newresponses:newarr
                })
                console.log("this is only array",this.state.newresponses);
                console.log("conventional responses",this.state.poll.responses)

            }

        });

    }
    editpoll(){
        Api.put('/api/polls/' + pollId, newVotesObj, (err, response) => {
            if (err) { 
                 console.log("Error: " + JSON.stringify(err)); 
                 return;
            }

            // Success so update the state with the correct scores
            /*

            var listLen = updatedList.responses.length;
            for (let i = 0; i < listLen; i++) {
                if (updatedList.responses[i]['response'] == selectedRadio)
                    updatedList.responses[i]['votes'] = totalVotes;
            }

            // Get doughnut to re-draw chart. (using a data store?)
            var votesSoFar = updatedList.responses.map(function(rv) { return rv.votes; });
            chartValues.datasets[0].data = votesSoFar
            this.setState({ 
              data: chartValues,
              list: updatedList
            });

            */

        },true);


    }

    valuechangetext(e){
        console.log("this is the id",e.target.id)
        var key = e.target.id;
        var newresponses = this.state.newresponses[key];

       this.setState({
           newresponses:e.target.value

       })

    }







    render(){
        console.log("state",this.state)
        console.log("this map",this.state.poll.responses)
        var newarr = this.state.newresponses;
       var responseinput =  this.state.poll.responses.map(function(i, index){
           return(

               <div key={index} >

           <input type="text" id={index} onChange={this.valuechangetext.bind(this)} value={this.state.newresponses[index]} /> <br /><br />
           </div>
               )

        }.bind(this));
        console.log("response input inside render",responseinput)

        return (
            <div>
            <h2>Edit the damn poll here!!</h2>
            <h4>{this.state.pollquestion}</h4>
            <p>author:{this.state.author}</p>
            <form onSubmit={this.handleedit}>
            {responseinput}
            <br/>
            <input type="submit" name="submitBtn"  value="Submit Edited Poll"/>
             </form>
            <button onClick={this.editpoll.bind(this)}>Edit Poll</button>
            <Link to="/">Back</Link>
            </div>

        )
    }

}

export default Editdamnpoll

```

到目前为止我对这个问题的研究

我查看了 stackoverflow 问题。每个答案都建议我应该用 "" 启动状态的键值对。如果它为 null 或未定义,则将其作为不受控制的组件响应启动。当我将其值设置为 this.state.... React 认为,我正在将不受控制的组件更改为受控组件。但是,正如你现在所看到的,我启动了所有具有一定价值的状态。所以,我不知道为什么我仍然看到这个警告信息?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    在第一次渲染时this.state.newresponses[index] 将寻找this.state.newresponses[0](来自第一个this.state.poll.responses 循环的索引)

    这还不存在,你有this.state.newresponses = [2]

    你可以改变初始状态,或者做这样的事情

    value={this.state.newresponses[index] || ''}

    【讨论】:

    • 谢谢。你真棒。有效!!你使用过 react 开发工具还是它经验丰富的眼睛?我也试图支持你的回答。但我收到消息说我的投票已被记录,但不会公开显示,因为我的声誉较低。
    • 我试图理解你的答案。最初我确实有 this.state.newresponses=[2] ,所以当它寻找 this.state.newresponses[0] 时。比那里有2个。为什么会抛出错误? @米切尔
    猜你喜欢
    • 2020-10-07
    • 2020-01-29
    • 2017-10-21
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    相关资源
    最近更新 更多