如何从文本输入更新redux的状态?
我试图做一个非常简单的" Hello World"带有文字输入。当有人输入文字输入时,它应该更新我的商店" searchTerm"值。
我无法弄清楚这些事情: 1.如何获取输入的值并将其传递给它" onChange"处理程序? 2."搜索"动作似乎被正确调用,但我的reducer函数从未使用过(没有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
});
答案 0 :(得分:7)
将动作创建者绑定到更改事件时,您应该使用this.props.search
:
<input type="text" placeholder="Search" onChange={(event) => this.props.search(event.target.value)} />