反应搜索栏,从另一个类调用函数

时间:2018-06-05 15:49:59

标签: django reactjs

大家好,我从我的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不是一个函数 谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

简短的回答是: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上出错。