如何在redux中发送onchange事件?

时间:2017-08-10 19:58:04

标签: javascript reactjs react-native dispatch

我在组件中创建了一个搜索框。所以我在父App.js外面调用onchange函数。现在我正在尝试调度该函数,如果我在搜索框中键入任何内容但我无法在我的课外访问该函数。

如何发送我的功能?

请在下面找到我的源代码:

import React, {Component} from "react";
import {connect} from "react-redux";
import { User } from "../components/User";
import { Main } from "../components/Main";
import Data from "../components/Data";
import MovieListing from '../components/MovieListing';
import Header from '../components/Header'
import { setName, getApiData } from "../actions/userActions";
import {apiFetch} from "../actions/dataActions"
import {searchFetch} from "../actions/searchActions"

class App extends Component {    

    constructor(props){
        super(props)
        this.searchQuery = this.searchQuery.bind(this);
    }

    searchQuery( query ) {
    }

    render() {        
        let dataSet=this.props.data.data.results;
        let imagePath = []
        let original_title = []
        let release_date = []
        let original_language = []
        if(dataSet){ 

            dataSet.forEach(function (value, key) {
                imagePath.push(<Data key={key} imagePath={value.backdrop_path} release_date={value.release_date} original_title={value.original_title} original_language={value.original_language} />)
                original_title.push(value.original_title)
            })
            return(
                <div className="wrapper">
                    <Header searchQuery = { this.searchQuery } />
                    <div className="movies-listing">
                        <div className="container">
                            <MovieListing imagePath={imagePath} release_date={release_date} original_title={original_title} original_language={original_language} />               
                        </div>
                    </div>
                </div>
            )

        }else{
            return(
                <div className="middle-loader">
                    <h1>Loading</h1>
                </div>
            )
        }
        // console.log("this.props",this.props);
    }

}

const mapStateToProps = (state) => {
  return {
      user: state.user,
      math: state.math,
      data: state.data,
      searchData: state.searchData
  };
};

const mapDispatchToProps = (dispatch) => {
    return dispatch(apiFetch()), {searchQuery: (query) => {searchFetch(query)}}
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

这里我无法访问{searchQuery: (query) => {searchFetch(query)}},因为在课堂外无法访问该功能。

帮助我们获得赞赏!!

1 个答案:

答案 0 :(得分:0)

mapDispatchToProps接受/传递调度函数,然后返回searchQuery函数作为道具。

const mapDispatchToProps = (dispatch) => {
  return {
    searchQuery: (query) => { dispatch(searchFetch(query)) }
  }
};

然后在Header组件中传递searchQuery prop

<Header searchQuery={ this.props.searchQuery } />