Update redux state with an input

牧云@^-^@ 提交于 2020-01-13 08:21:05

问题


How can I update redux's state from a text input?

I'm trying to do a very simple "Hello World" with a text input. When someone types into the text input, it should update my store's "searchTerm" value.

I can't figure out these things: 1. How can I get and pass the input's value into it's "onChange" handler? 2. The "search" action seems to be called correctly, but my reducer function is never used (no console.log).

SearchForm.js (component)

import React, {Component, PropTypes} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {search} from 'redux/modules/search-term';

@connect(
  null,
  dispatch => bindActionCreators({ search }, dispatch)
)

export default class SearchForm extends Component {
  static propTypes = {
    search: PropTypes.func.isRequired,
  }

  render() {
    return (
      <input type="text" placeholder="Search" onChange={search} />
    );
  }
}

search-term.js (action & reducer)

const SEARCH = 'redux-example/repo-filter/SEARCH';

const initialState = {
  searchTerm: null
};

export default function reducer(state = initialState, action = {}) {
  console.log("reducing");

  switch (action.type) {
    case SEARCH:
      return {
        searchTerm: action.term
      };
    default:
      return state;
  }
}

export function search(term) {
  return {
    type: SEARCH,
    term
  };
}

reducer.js

import { combineReducers } from 'redux';
import multireducer from 'multireducer';
import { routerStateReducer } from 'redux-router';

import search from './search-term';

export default combineReducers({
  router: routerStateReducer,
  search
});

回答1:


You should use this.props.search when binding the action creator to the change event:

<input type="text" placeholder="Search" onChange={(event) => this.props.search(event.target.value)} />



来源:https://stackoverflow.com/questions/34474272/update-redux-state-with-an-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!