TypeError:无法读取未定义的属性“ props”

时间:2019-09-02 08:50:34

标签: reactjs redux react-redux

我尝试将redux添加到我的todo应用程序中,并以react编码。一开始很容易,我为CRUD应用设置了版本,清单和所有内容。但是,有一项行动是缺少消除措施。我在动作js文件中为redux设置了remove方法,但是当我想像以前用this.props.deleteTodo调用该版本的动作时,会出现此错误:

class TodosList extends Component {
  constructor() {
    super();
    this.state = { todos: [] };
  }

  componentDidMount() {
    //TODO Give this action to todoAction
    axios
      .get("/todos")
      .then(response => {
        this.setState({ todos: response.data });
      })
      .catch(function(error) {
        console.log(error);
      });
  }

  todoList() {
    return this.state.todos.map(function(currentTodo, i) {
      return (
        <tr key={i}>
          <td className={currentTodo.todo_completed ? "completed" : ""}>
            {currentTodo.todo_description}
          </td>
          <td className={currentTodo.todo_completed ? "completed" : ""}>
            {currentTodo.todo_responsible}
          </td>
          <td className={currentTodo.todo_completed ? "completed" : ""}>
            {currentTodo.todo_priority}
          </td>
          <td>
            <Link to={"/edit/" + currentTodo._id}>Editer</Link>
            <button
              className="btn btn-primary"
              // I can't read this.props here to get the method
              // dispatched
              onClick={this.props.deleteTodo(currentTodo._id)}
            >
              Supprimer
            </button>
          </td>
        </tr>
      );
    });
  }
  render() {
    return (
      <div>
        <h3>Todos List</h3>
        <table className="table table-striped" style={{ marginTop: 20 }}>
          <thead>
            <tr>
              <th>Description</th>
              <th>Responsible</th>
              <th>Priority</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>{this.todoList()}</tbody>
        </table>
      </div>
    );
  }
}
TodosList.propTypes = {
  deleteTodo: PropTypes.func.isRequired,
  errors: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  errors: state.errors
});

export default connect(
  mapStateToProps,
  { deleteTodo }
)(TodosList);
  

TypeError:无法读取未定义的属性“ props”

1 个答案:

答案 0 :(得分:1)

deleteTodo不是传递给TodosList组件的道具。

因此,请在propTypes中将其删除。

您可以拥有:

import { deleteTodo } from './actionCreators' // deleteTodo from actionCreator
                                              // not passed s prop

class TodosList extends Component {

  handleClick = (event) => {
    this.props.deleteTodo(currentTodo._id)
  }

  todoList() {
    return this.state.todos.map((currentTodo, i) => ( // arrow function
       <tr key={i}>
          <td>
            <button
              onClick={handleClick} // pass arrow function
            />
          </td>
      </tr>
    ))
  }

  render() { ... }
}

connect(mapStateToProps, { deleteTodo })(TodosList)
相关问题