React / Redux搜索栏无法正常工作

时间:2018-05-03 13:31:19

标签: javascript reactjs redux react-redux searchbar

我的TODO列表上有一个搜索栏:

import React, { Component } from 'react';
import { FilterTasks } from '../../redux/actions/searchbar';
import reducers from '../../redux/reducers';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';

class SearchBar extends Component {
    render() {
      const {search, value} = this.props;

      return (
          <input
            className="form-control"
            placeholder = "Filter Tasks"
            onChange={(e) => FilterTasks(e.target.value)}
            value={value} />
      );
    }
  } 

  function mapStateToProps({tasks}) {
    return {value: tasks.value};
  }

  function mapDispatchToProps(dispatch) {
    return bindActionCreators({FilterTasks}, dispatch);
  }

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

以下是我要过滤的行动:

export const SEARCH = 'SEARCH';

export function FilterTasks(value) {
  return {type: SEARCH, value};
}

我的搜索栏缩减器:

import {SEARCH} from '../actions/searchbar';

const initialState = {}

export default function SEARCHREDUCER(state = initialState, action) {
  switch(action.type) {
    case SEARCH: {
      const {value} = action;
      const tasks = state.contents.filter((val) => val.includes(value));
      return {...state, value, tasks};
    }
    default:
      return state;
  }
}

我的指数缩减器:

import { combineReducers } from 'redux';
import SEARCHREDUCER from '../reducers/searchbar';

const TaskReducer = (state = [] ,action) => {
    switch (action.type){
    case 'ADD_TASK':
    state = state.concat(action.payload);
    break;
    case 'DELETE_TASK':
  state = state.tasks.filter(task => task !== action.payload)
    break;
    }
    return state;
},

reducers = combineReducers({
    tasks : TaskReducer,
    SEARCHREDUCER 
});

export default reducers;

我的TasksList类应该呈现已过滤的列表:

import React, { Component } from 'react';
import {connect} from 'react-redux';
import Task from '../task'

class TaskList extends Component {
    render(){
        return(
            <table>
                <thead>
                    <tr>
                        <th>Tasks</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {this.props.tasks.map((task,index) => <Task key={index} task={task} />)}
                </tbody>
            </table>
        );
    }
}

function MapStateToProps(state){
    return{
        tasks:state.tasks,
    }
}

export default connect (MapStateToProps)(TaskList);

我的问题是,当我在搜索栏上输入一个条目时,任务列表根本不会改变,它没有显示任何类型的错误。我在这里失踪了什么?

1 个答案:

答案 0 :(得分:1)

FilterTasks(e.target.value)应该是this.props.FilterTasks(e.target.value),否则它会从mapDispatchToProps未绑定到Redux的操作中调用导入的函数。

此外,您的TaskReducerSEARCHREDUCER错误。 reducer变量是具有合并状态的变量,而不是TaskReducerSEARCHREDUCER

您应该将搜索字符串保持在状态,并使用TaskListthis.props.tasks.filter(<insert filter function>).map(<insert map function>)内进行过滤。