React/Redux TODO列表搜索栏无法正常工作求助
Fixing Your Non-Working React-Redux Search Bar
Hey there, let's break down why your search bar isn't functioning and get it sorted out step by step. Looking at your code, there are a few key issues preventing it from working with Redux properly:
Key Issues in Your Current Code
- Directly calling the action creator without dispatching it: You're invoking
FilterTasks(e.target.value)directly in theonChangehandler, but Redux action creators need to be dispatched to the store to trigger state updates. - Incomplete Redux
connectconfiguration: Your code cuts off atfunc...—this is where you need to define how the component connects to the Redux store (mapping state and actions to props). - Unbound action creators: While you imported
bindActionCreators, you didn't properly wire it up to make the action available via the component's props.
Fixed Complete Code
Here's the corrected version with explanations:
import React, { Component } from 'react'; import { FilterTasks } from '../../redux/actions/searchbar'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; class SearchBar extends Component { render() { // Destructure the bound action and state value from props const { filterTasks, value } = this.props; return ( <input className="form-control" placeholder="Filter Tasks" // Use the bound action from props to dispatch the action onChange={(e) => filterTasks(e.target.value)} value={value} /> ); } } // Map Redux store state to component props const mapStateToProps = (state) => { // Adjust this path to match your reducer's structure // Example: if your root reducer has a "search" slice with a "value" field return { value: state.search.value }; }; // Bind action creators to dispatch and map to props const mapDispatchToProps = (dispatch) => { return bindActionCreators({ // Map the FilterTasks action creator to a camelCase prop for consistency filterTasks: FilterTasks }, dispatch); }; // Connect the component to the Redux store export default connect(mapStateToProps, mapDispatchToProps)(SearchBar);
Additional Checks to Ensure It Works
Verify Your Reducer Handles the Action: Make sure your search reducer correctly responds to the
FilterTasksaction type. Example reducer code:// redux/reducers/searchbar.js const initialState = { value: '' }; export default function searchReducer(state = initialState, action) { switch(action.type) { // Match the action type used in your FilterTasks action creator case 'FILTER_TASKS': return { ...state, value: action.payload }; default: return state; } }Confirm Reducer is Added to Root Reducer: Ensure your search reducer is included in the combined root reducer:
// redux/reducers/index.js import { combineReducers } from 'redux'; import searchReducer from './searchbar'; const rootReducer = combineReducers({ search: searchReducer }); export default rootReducer;
内容的提问来源于stack exchange,提问作者pedrodotnet
相关产品推荐
相关产品推荐

