反应形式handleChange不更新状态

时间:2019-09-22 05:29:59

标签: react-redux

表单输入的onChange未更新状态。动作和reducer正常启动,后端rails API已更新,但状态未更改,并且DOM中没有任何内容。

我已使用控制台日志来确保操作和减速器正常工作。

import React, { Component } from 'react';
import { Button, Form } from 'semantic-ui-react'
import { connect } from 'react-redux'


class TaskInput extends Component {
  constructor() {
    super()
    this.state = {
      name: ""
    }
  }
  handleChange = (e) => {
    this.setState({
      name: e.target.value
    })
  }

  handleSubmit = (e) => {
    e.preventDefault()
    this.props.addTask({name: this.state.name}, this.props.goal.id)
    this.setState({
      name: ''
    })
  }

  render() {
    return (
      <Form className="new-task-form" onSubmit={(e) =>this.handleSubmit(e)}>
       <Form.Field>
         <label className="form-label">Add Task</label>
         <input id="name" required value={this.state.name} onChange={(e) => this.handleChange(e)} />
       </Form.Field>
       <Button basic color='purple' type="submit">Add Task</Button>
       <hr/>
     </Form>
    )
  }
}

export default connect()(TaskInput)




import React, { Component } from 'react'
import { addTask, deleteTask } from '../actions/tasksActions'
import { connect } from 'react-redux'
import { fetchGoal } from '../actions/goalsActions'
import Tasks from '../components/Tasks/Tasks';
import TaskInput from '../components/Tasks/TaskInput';

class TasksContainer extends Component {

  componentDidMount() {
    this.props.fetchGoal(this.props.goal.id)
  }

  render(){
    return(
      <div>
        <TaskInput
          goal={this.props.goal}
          addTask={this.props.addTask}
          />

        <strong>Tasks:</strong>
        <Tasks
          key={this.props.goal.id}
          tasks={this.props.goal.tasks}
          deleteTask={this.props.deleteTask}
        />
        </div>
    )
  }
}
const mapStateToProps = state => ({
  tasks: state.tasksData
})


export default connect(mapStateToProps, { addTask, deleteTask, fetchGoal })(TasksContainer);



export default function taskReducer(state = {
  loading: false,
  tasksData: []
},action){
  switch(action.type){
    case 'FETCH_TASKS':
      return {...state, tasksData: action.payload.tasks}
    case 'LOADING_TASKS':
      return {...state, loading: true}
    case 'CREATE_TASK':
      console.log('CREATE Task', action.payload )
      return {...state, tasksData:[...state.tasksData, action.payload.task]}
    case 'DELETE_TASK':
      return {...state, loading: false, tasksData: state.tasksData.filter(task => task.id !== action.payload.id )}

    default:
      return state;
    }
}

handleSubmit将操作调用给addTask。 handleChange更新状态并在DOM中呈现新任务。 handleSubmit正在工作。 handleChange不是。

0 个答案:

没有答案