使用输入更新Redux状态 [英] Update redux state with an input

查看:73
本文介绍了使用输入更新Redux状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从文本输入中更新redux的状态?

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

我正在尝试使用文本输入创建一个非常简单的"Hello World".当有人输入文本输入时,它应该更新我商店的"searchTerm"值.

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.

我不知道这些事情: 1.如何获取输入的值并将其传递到其"onChange"处理程序中? 2.搜索"操作似乎被正确调用,但是我的reducer函数从未使用过(没有console.log).

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 (组件)

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 (动作和归约器)

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
});

推荐答案

将动作创建者绑定到更改事件时,应使用this.props.search:

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)} />

这篇关于使用输入更新Redux状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆