I have a react component that will throws an error when I try to dispatch a redux action. Here is the component:
import React from 'react';
import { connect } from 'react-redux';
import { createBook } from './actions/books';
import './InputForm.css';
export class InputForm extends React.Component {
onFormSubmit(event) {
event.preventDefault();
let newBook = {
title: this.titleInput.value,
author: this.authorInput.value,
description: this.descriptionInput.value
}
this.props.dispatch(createBook(newBook));
}
render() {
return (
<div>
<form onSubmit={event => this.onFormSubmit(event)}>
<input className="form-input" placeholder="Title" ref={input => this.titleInput = input} />
<input className="form-input" placeholder="Author" ref={input => this.authorInput = input} />
<input className="form-input form-text-area" placeholder="Description" ref={input => this.descriptionInput = input} />
<button className="form-button" type="submit">Submit</button>
</form>
</div>
)
}
}
export default connect()(InputForm);
This is the line that creates the problem:
this.props.dispatch(createBook(newBook));
I'm not sure what's going on. Here is the error I get:
Uncaught TypeError: this.props.dispatch is not a function
at InputForm.onFormSubmit (InputForm.js:15)
at onSubmit (InputForm.js:21)
at HTMLUnknownElement.callCallback
I have another component set up almost identically using a different action. It works fine. Here is that component if anyone wants to compare:
import React from 'react';
import './Book.css';
import { deleteBook } from './actions/books';
import { connect } from 'react-redux';
export class Book extends React.Component {
onDelete(event) {
this.props.dispatch(deleteBook(this.props.id));
}
render() {
return (
<div className="book-container">
<h4>{this.props.title}</h4>
<p>{this.props.author}</p>
<p>{this.props.description}</p>
<p>{this.props.id}</p>
<button className="book-delete-button" onClick={event => this.onDelete(event)}>Delete</button>
</div>
)
}
}
export default connect()(Book);
Dunno what's going on here. Please help!
答案 0 :(得分:3)
这里似乎至少有两个可能导致问题的问题。
这取决于您import
组件的方式。您正在出口2
每个模块中的组件:
如果您导入指定的导出:
import { InputForm } from './path';
您不会redux
相关props
,因为这不是。{
连通组件。
这就是为什么你的其他连接组件之一工作正常,即使它看起来具有相同的代码和结构模式
您可能按照应有的方式导入(default
导入)。
确保导入default
组件:
import InputForm from './path';
onFormSubmit
,所以我希望this
成为。{1}}
触发事件的元素。虽然我认为如果那是
问题,无论如何你会得到一个不同的错误。答案 1 :(得分:0)
我在容器组件中导入了断开连接的版本。愚蠢的错误。