django - React Search Bar ,从另一个类调用函数
问题描述
大家好,我正在从我的 api 获取数据,我尝试设置这样的搜索栏:
import React, { Component } from "react";
import ProductsIndex from "./search_bar";
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: "" };
this.onInputChange = this.onInputChange.bind(this);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onInputChange(event) {
this.setState({ term: event.target.value });
}
onFormSubmit(event) {
event.preventDefault();
ProductsIndex.renderProducts(this.state.term)
// this.props.fetchWeather(this.state.term);
this.setState({ term: "" });
}
render() {
return (
<form onSubmit={this.onFormSubmit} className="input-group">
<input
placeholder="Get a five-day forecast in your favorite cities"
className="form-control"
value={this.state.term}
onChange={this.onInputChange}
/>
<span className="input-group-btn">
<button type="submit" className="btn btn-secondary">Submit</button>
</span>
</form>
);
}
}
export default SearchBar;
在我的 onSubmit 函数中,尝试从我的类 ProductsIndex 调用我的函数 renderProducts :
class ProductsIndex extends Component {
componentDidMount() {
this.props.fetchProducts();
}
renderProducts(term) {
return _.map(this.props.products, product => {
if(product.name==term) {
return (
<tr key={product.name}>
<td>{product.name}</td>
<td>{product.product_category.name}</td>
<td>{product.price}</td>
</tr>
);
}
});
}
render(){
return(
<div>
<table className="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Name</th>
<th>Category</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{this.renderProducts()}
</tbody>
</table>
</div>
);
}
}
function mapStateToProps(state) {
return {products: state.products}
}
export default connect(mapStateToProps, {fetchProducts})
(ProductsIndex);
但这不起作用,我收到此错误:未捕获的 TypeError:_search_bar2.default.renderProducts 不是函数谢谢您的帮助
解决方案
简短的回答是:ProductsIndex.prototype.renderProducts
正确的答案是:术语的状态应该由层次结构中更高的组件拥有。SearchBar 触发父组件中的状态更改,并向下渗透到 ProductIndex。您的层次结构中可能已经有一个适合此的组件,但是如果您为此目的显式添加一个组件,它可能看起来会是这样。
export class SharedParent extends React.Component {
constructor() {
super();
this.state = {
term: ""
};
//I use this style for methods, you can also use fat arrows to ensure 'this' is properly set
this.setTerm = this.setTerm.bind(this);
}
setTerm(term) {
//beware current best practice is to pass a fucntion
//not an object to setState
this.setState({ term });
}
render() {
return [
<ProductIndex key="a" term={this.state.term} {...this.props.productProps} />,
<SearchBar key="b" setTerm={this.setTerm} {...this.props.searchProps}/>
];
}
}
PS:我建议也使用 Redux 或其他状态管理解决方案。不过,Redux 不会出错。
推荐阅读
- c++ - 不运行 std::min & std::max 算法头文件
- python - 从数据框列表中弹出所有数据框
- java - java中函数的方法极值
- java - 即使在使用 AsyncTask 之后,编舞者也会跳帧(最多 400 个!)
- c++ - 通过左值引用传递与在构造函数中通过值传递
- join - 来自同一个表的连接代码和描述,用逗号分隔
- c++ - Stack和Heap关于内存地址的问题
- javascript - 有人可以帮我解释为什么 JS 不能在 HTML 中工作吗?
- swift - 使用 Kingfisher activityIndicator 时 UICollectionViewCell 大小错误
- qt - 自定义 QML TabButton