setState()不采用其他参数(e)来更改值

 收藏

我想将状态的先前值附加到输入框的当前值 但是当我使用setState函数时,以某种方式不允许将事件作为参数传递。

问题: setState(prev,props,e) setState函数未检测到第三个参数(e)。

e.target.value未定义

这是我的代码:

import React , {Component} from 'react'
class Todo extends Component{
    constructor(){
        super()
        this.state={toDo:[],currentInput:"name"}
        // bind the events
        this.addItem=this.addItem.bind(this)
        this.changeList=this.changeList.bind(this)


    }

    addItem(e){
        // prevent default 
        e.preventDefault();

        // this part is left
    }
    changeList(e){


        this.setState(function (prev,props,e){
            console.log(prev.currentInput)
            return {currentInput:prev.currentInput+e.target.value} // this part is causing problem
        })
    }


    render(){
        return(
            <div className="App">
               <h1>Add your tasks</h1> 
            <form onSubmit={this.addItem}>
                <input type="text" value={this.state.currentInput} onChange={this.changeList} ></input>
                <input type="submit"></input>

            </form>
                <div className="List">
                    <h3>Remaining items:-</h3>
                    <ul>

                    </ul>
                </div>
            </div>
        )
    }


}

export default Todo
回复
  • Gold 回复

    That's not how setState works, you can't pass additional arguments, if you pass a function, React will invoke it passing in the state and the props as arguments

    You also don't want to append to the previous input state as e.target.value contains the full input value

  • setState(prev,props,e)setState函数未检测到第三个参数(e)。

    It means the setState only accepts two params, but you are using three prev,props,e.

    由于您可能只需要其中之一

    this.setState(prevState => ({
      currentInput: prevState.currentInput + e.target.value
    }))
    

    对于以前的状态,使用第一个就足够了。