首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将搜索值从一个组件传递到另一个组件

如何将搜索值从一个组件传递到另一个组件
EN

Stack Overflow用户
提问于 2018-07-24 00:32:54
回答 1查看 55关注 0票数 0

大家好,我正在尝试做一个简单的搜索栏来搜索我的firebase数据库基于搜索栏查询。我正在尝试从1个组件获取输入值,然后在组件2中使用firebase查询根据组件1的输入值显示结果。谁能告诉我我做错了什么?谢谢

1个组件

代码语言:javascript
复制
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { updateFilter } from '../../actions/filtered';
import { CarsRef, timeRef } from '../admin/reference';
import Searchresults from './searchresult';


class TopSearchBar extends Component {
  state = {
    make: '',
    body: '',
    priceRange: ''
  }
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.updateFilter(this.state);

    this.props.history.push('/cars2')

  }





  render(){
    let content = null;

     if (content !==null ) {
        <Searchresults make={this.state.make} />
}


else {

  <p> h </p>

}

    let searchMake = ["Audi","Honda","Lamborghini","Maserati", "Subaru","Toyota"];

    let cars = {
      Audi: [ {body: "Sedan"}, {body: "Coupe"}, {body: "SUV"} ],
      Honda: [ {body: "Sedan"}, {body: "Van"}, {body: "SUV"} ],
      Lamborghini: [ {body: "Coupe"} ],
      Maserati: [ {body: "Coupe"}, {body: "SUV"} ],
      Mercedes: [ {body: "Convertible"}, {body: "Coupe"} ],
      Subaru: [ {body: "Hatchback"} ],
      Toyota: [ {body: "SUV"}, {body: "Sedan"}, {body: "Truck"} ]
    }

    let makes = searchMake.map((make, i) => {
      return (
        <option key={i} value={make}>
          {make}
        </option>
      )
    })

    if(this.state.make) {
      var body = cars[this.state.make].map((make, i) => {
        return (
          <option key={i} value={make.body}>
              {make.body}
          </option>)
      })
    }

    return(

      <div className="top-search-bar">
        <div className="container text-align">
          <form onSubmit={this.handleSubmit}>
            <div className="row">
              <div className="col-3">
                <select className="form-control"
                    value={this.state.make}
                    onChange={(e)=>this.setState({make: e.target.value})}
                  >
                  <option value="" disabled selected>Make</option>
                    {makes}
                </select>
              </div>
              <div className="col-3">
                <select className="form-control"
                  value={this.state.body}
                  onChange={(e)=>this.setState({body: e.target.value})}
                  >
                    <option value="" disabled selected>Body Type</option>
                    { makes ? body : null }
                  </select>
              </div>
              <div className="col-3">
                <select className="form-control"
                  value={this.state.priceRange}
                  onChange={(e)=>this.setState({priceRange: e.target.value})}
                  >
                    <option value="" disabled selected>Price</option>
                    <option value="lowHigh">Low To High</option>
                    <option value="highLow">High To Low</option>
                  </select>
              </div>
              <div className="col-3">
                  <button type="submit" className="btn btn-success btn-block" onClick={this.handleSubmit}>Search</button>
              </div>
            </div>
            {content}
          </form>

        </div>
      </div>

    );
  }
}

第二个组件

代码语言:javascript
复制
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Car from './car';
import { CarsRef, timeRef } from '../admin/reference';

import { CardImg, Button, Row, Col, Table } from 'reactstrap';
import { getsinglecar } from '../../actions/cars';
import Icon from 'react-icons-kit';
import { bin } from 'react-icons-kit/icomoon';
import { getCarsThunk } from '../../actions/cars';
import { Link } from 'react-router-dom';



    class Searchresults extends Component {
      // ...



      state = {
        Cars: [],
       Carsloading: true
      };
      handleDelete = (id) => {
        this.props.deleteCar(id);
      }




     componentWillMount() { 


    alert(`${this.props.make}`); // returns undefined 

     CarsRef.orderByChild(`${this.props.make}`).startAt(`${this.props.make}`).endAt(`${this.props.make}`).on('value', (snap) => {

     let Cars = []
        snap.forEach((child) => {
       Cars.push({ ...child.val(), key: child.key });
        });

          console.log(Cars);
          this.setState({ Cars: Cars, CarsLoading: false });
        });

    }
      render() {
        const { Cars, CarsLoading } = this.state;
        const orderedcars = Cars;

        let carList;


        if (CarsLoading) {
          carList = <div className="TaskList-empty">Loading...</div>;
        } else {

          carList = (
            <ul className="TaskList">
              {Cars.map(car => (
                <div>
                  <Row>
                    <Col md="12">
                      <div className="card border-secondary mb-3">
                        <div className="card-header text-success">
                          <h4>
                            <Link to={`/cars/${car.id}`}>

                            </Link>
                          </h4>
                        </div>
                        <div className="card-body">
                          <Row>
                            <Col md="5">
                              <CardImg
                                className="carlist-margin"
                                top
                                width="100%"
                                src={car.link}
                                alt={car.make}
                              />
                            </Col>
                            <Col md="4">
                              <Table className="striped">
                                <tbody>
                                  <tr>
                                    <td>Engine:</td>
                                    <td>{car.engine}</td>
                                  </tr>
                                  <tr>
                                    <td>Drive Type:</td>
                                    <td>{car.drive_type}</td>
                                  </tr>
                                  <tr>
                                    <td>Body:</td>
                                    <td>{car.body_type}</td>
                                  </tr>
                                  <tr>
                                    <td>Exterior Color:</td>
                                    <td>{car.ext_color}</td>
                                  </tr>
                                  <tr>
                                    <td>Interior Color:</td>
                                    <td>{car.int_color}</td>
                                  </tr>
                                  <tr>
                                    <td>Transmission:</td>
                                    <td>{car.transmission}</td>
                                  </tr>
                                  <tr>
                                    <td>VIN:</td>
                                    <td>{car.vin}</td>
                                  </tr>
                                </tbody>
                              </Table>
                            </Col>
                            <Col md="3">
                              <Table className="striped">
                                <tbody>
                                  <tr>
                                    <td className="text-primary text-right">
                                      <strong>MSRP:</strong>
                                    </td>
                                    <td className="text-primary text-right">
                                      <strong>${car.price}</strong>
                                    </td>
                                  </tr>
                                  <tr>
                                    <td className="text-danger text-right">
                                      Dealer Discount:
                                    </td>
                                    <td className="text-danger text-right">
                                      {car.sale}%
                                    </td>
                                  </tr>
                                  <tr>
                                    <td className="text-primary text-right">
                                      <strong>Total:</strong>
                                    </td>
                                    <td className="text-primary text-right">
                                      <strong>
                                        ${car.price - (car.price * car.sale) / 100}
                                      </strong>
                                    </td>
                                  </tr>
                                  <tr>
                                    <td className="text-primary text-right">
                                      Est. Lease:
                                    </td>
                                    <td className="text-primary text-right">
                                      $230/m*
                                    </td>
                                  </tr>
                                  <tr>
                                    <td className="text-primary text-right">
                                      Est. Finance:
                                    </td>
                                    <td className="text-primary text-right">
                                      $330/m*
                                    </td>
                                  </tr>
                                  <tr>
                                    <td className="text-right" />
                                    <td className="text-right">
                                      <Link to={`/cars/${car.id}`}>
                                        <Button className="btn btn-success">
                                          More
                                        </Button>
                                      </Link>
                                    </td>
                                  </tr>
                                </tbody>
                              </Table>
                            </Col>
                          </Row>
                        </div>
                      </div>
                    </Col>
                  </Row>
                </div>
              ))}
            </ul>
          );
        }

        return carList;
      }
    }


    export default Searchresults

;
EN

回答 1

Stack Overflow用户

发布于 2018-07-24 03:23:46

你必须将你的第二个组件连接到Redux Store,并创建一个MapStateToProps来访问你需要的属性。

首先创建MapStateToProps

代码语言:javascript
复制
 const mapStateToProps = state => {
   return {
      make: state.make// place here the name of the property in your reducer
   }
 }

然后将其连接到Redux Store。

代码语言:javascript
复制
 export default connect(mapStateToProps)(Searchresults)

从现在开始,你将可以访问道具"make“(或者你在MapStateToProps上给出的任何名字)。

看看这个来自Redux Documentation的例子

如果你向我展示你的行动,我可能会在我的回应中更具体。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51483487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档