如何使用带有redux thunk

时间:2017-12-20 21:47:30

标签: reactjs react-native redux redux-thunk

我有一个名为searchResult()的动作创建者,它从Firebase获取数据,然后根据另一个名为SearchReducer的减速器(由动作创建者searchChanged()创建)对称为“搜索”的状态进行过滤。以下是代码的外观:

 export const searchResult = () => {
    const { currentUser } = firebase.auth();
       return (dispatch, getState) => {

    firebase.database().ref(`/users/${currentUser.uid}/entries`)
       .orderByChild('uid')
         .on('value', snapshot => {
          const myObj = snapshot.val();
          const { search } = getState().searching;

          const list = _.pickBy(myObj, (((value) => 
             value.make.indexOf(search) !== -1 || 
             value.model.indexOf(search) !== -1) && ((value) => 
             value.sold === false)));


             dispatch({ type: SEARCH_RESULT_SUCCESS, payload: list });
     });
    };
   };

代码运行,但没有任何过滤。使用redux调试器,我可以看到“搜索”发生了变化。我的语法有问题吗?任何帮助,将不胜感激。这是我的其他代码:

Action Creator searchChanged():

 export const searchChanged = (text) => {
   return {
      type: SEARCH_CHANGED,
      payload: text
     };
   };

Reducer SearchReducer:

 import {
    SEARCH_CHANGED,
 } from '../actions/types';

 const INITIAL_STATE = {
   search: '',
 };

 export default (state = INITIAL_STATE, action) => {
   switch (action.type) {
     case SEARCH_CHANGED:
       return { ...state, search: action.payload };
   default:
       return state;
   }
  };

searchResult()的Reducer名为EntryReducer:

import {
  SEARCH_RESULT_SUCCESS,
  ENTRY_FETCH_SUCCESS,
  SOLD_RESULT_SUCCESS
} from '../actions/types';

const INITIAL_STATE = [];


export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case ENTRY_FETCH_SUCCESS:
      return action.payload;
    case SEARCH_RESULT_SUCCESS:
      return action.payload;
    case SOLD_RESULT_SUCCESS:
      return action.payload;
    default:
      return state;
  }
};

这是combineReducers()函数:

import { combineReducers } from 'redux';
import AuthReducer from './AuthReducer';
import EntryFormReducer from './EntryFormReducer';
import EntryReducer from './EntryReducer';
import SearchReducer from './SearchReducer';
import PasswordReducer from './PasswordReducer';

export default combineReducers({
  auth: AuthReducer,
  entryForm: EntryFormReducer,
  employees: EntryReducer,
  searching: SearchReducer,
  pw: PasswordReducer
});

这里调用searchChanged()后跟searchResult():

class Search extends Component {

   //onSearchChange() is just the onChangeText binding for the text input.
   onSearchChange(text) {
     this.props.searchChanged(text);
     searchResult();
 }

=========================新编辑的部分=================== ============

现在我在我的搜索组件中使用mapDispatchToProps。但是,我仍然遇到错误,或者当我输入搜索输入时没有任何反应。整个组件看起来像这样(它返回一个错误,searchResult不是一个函数。我从https://learn.co/lessons/map-dispatch-to-props-readme得到我的指示):

import React, { Component } from 'react';
import { View } from 'react-native';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Icon } from 'react-native-vector-icons';
import { searchChanged, searchResult } from '../actions';
import Card from './common/Card';
import CardSection from './common/CardSection';
import Input from './common/Input';


class Search extends Component {

  onSearchChange(text) {
    this.props.searchChanged(text);
    this.store.props.dispatch(searchResult());
  }


  render() {
    return (
      <View>

       <Input
         placeholder="Search"
         onChangeText={this.onSearchChange.bind(this)}
         value={this.props.search}
         returnKeyType={'search'}
       />

       </View>
   );
  }
 }


 const mapStateToProps = state => {

   return {
     search: state.searching.search
    };
  };

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({
    searchResult: searchResult
  }, dispatch);
};

export default connect(mapStateToProps, { searchChanged }, mapDispatchToProps)(Search);

仅使用:

 onSearchChange(text) {
this.props.searchChanged(text);
dispatch(searchResult());
}

返回一个错误,即dispatch是一个未声明的变量。如何正确格式化此组件,以便它正确理解mapDispatchToState?

1 个答案:

答案 0 :(得分:1)

从您的应用级代码。

从&#39; ../ actions / list-actions&#39;;

导入searchResult
onSearchChange(text) {
    this.props.searchResult(text);

  }


const mapStateToProps = (state) => {

    return {
        yourListName: state.yourListName,
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        searchResult: (data) => dispatch(searchResult(data)),
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Search)

然后在行动......

export const SEARCH_RESULT_SUCCESS = list => ({
    type: 'SEARCH_RESULT_SUCCESS',
    payload: list,
});

   export const searchResult = (data) => dispatch {
    const { currentUser } = firebase.auth();
       return (dispatch, getState) => {

    firebase.database().ref(`/users/${currentUser.uid}/entries`)
       .orderByChild('uid')
         .on('value', snapshot => {
          const myObj = snapshot.val();
          const { search } = getState().searching;

          const list = _.pickBy(myObj, (((value) => 
             value.make.indexOf(search) !== -1 || 
             value.model.indexOf(search) !== -1) && ((value) => 
             value.sold === false)));
        //!!!Do you filtering HERE based on the data (or search value) passed in 
            through the app level. 
        //Then dispatch the save of the newly edited list to your redux store.
        //Or based on your use case take just the article that matched, and store 
          it to a searched category in the store.  
             dispatch(SEARCH_RESULT_SUCCESS(list));
     });
    };
   };

};