React form input not changing on edit

2019-08-02 19:02发布

问题:

I have an app where I am trying to allow users to update the text of a "task/to-do" item. When the user hits the "edit" button, the edit component renders properly, but the input fields don't allow editing.

I'm suspicious I'm not passing props properly or updating state properly, but the React tab of the Chrome dev tools seems to have things right...

Here's the first part of the component:

class Task extends Component {
  constructor(props) {
    super(props)
    this.state = {
      editingTask: false,
      id: this.props.id,
      task: this.props.task,
      timeNeeded: this.props.timeNeeded,
      dueDate: this.props.dueDate
    }

....

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

........

And here is the render:

    render () {
const { task, timeNeeded, timeLeft, dueDate, id } = this.props
if (this.state.editingTask) {
  return (
    <div className='addTaskFormDiv'>
      <form onSubmit={this.handleSubmit}>
        <label>
      Task:
          <input type='text' name='task' value={task} onChange={this.handleChange} />
        </label>
        <label>
        Time needed:
          <input type='text' name='timeNeeded' value={timeNeeded} onChange={this.handleChange} />
        </label>
        <label>
        Due date:
          <DatePicker
            className='dueDate'
            dateFormat='YYYY/MM/DD'
            // selected={this.props.dueDate}
            onChange={this.handleDateChange} />
          {/* Date picker is not closing on selection. */}
        </label>
        <button className='formSubmit' onClick={this.handleSubmit} value='Submit'>Done</button>
      </form>
    </div>
  )

......

Full code on GitHub (development branch), the Task.js file is the one I am working on: https://github.com/emachaffie/timeboxer/tree/development

Any help is much appreciated!

回答1:

It's all because you update this.state with calling .setState() but takes values from this.props in line

const { task, timeNeeded, timeLeft, dueDate, id } = this.props

And since onChange is called per every single key press input is re-rendered with value from .props and it looks like "it does not allow editing"(but actually it allows).