我正在使用redux-form
和formValueSelector
从字段中获取输入值。我希望获得改变的价值,但在我的函数调用@@redux-form/CHANGE
后调用onChange
动作。所以我没有更新价值。我的代码:
export class PersonFilter extends React.Component {
constructor(props) {
super(props);
}
filterByName = (event, searchName) => {
//here searchName is getting old value
store.dispatch({type: 'PERSON_FILTER_BY_NAME', payload: {name: searchName}});
};
render() {
const {
searchName
} = this.props;
return (
<form className="person person--filter" onSubmit={e => {
e.preventDefault();
this.filterByName(e, searchName)
}}>
<Field
onChange={e => {
this.filterByName(e, searchName)
}}
className="person__input" icon="search"
name="searchName" component={renderField} type="text"
placeholder="Name"/>
</form>
);
}
}
PersonFilter = reduxForm({
form: 'filter',
initialValues: {
searchName: store.getState().personsFilterReducer.filterByName
}
})(PersonFilter);
const selector = formValueSelector('filter');
PersonFilter = connect(state => {
const searchName = selector(state, 'searchName');
return {
searchName
}
})(PersonFilter);
和包装器组件:
class Persons extends React.Component {
constructor() {
super();
}
render() {
return (
<div>
<PersonFilter/>
</div>
};
}
}
答案 0 :(得分:1)
不要只是将onChange传递给你应该setState
的动作,首先在包装器组件构造函数中初始化状态this.state
,并确保将 props 传递给构造函数好吧,然后在onChange函数this.setState
中设置一个状态并绑定它。
像这样:
包装组件
class Persons extends React.Component {
constructor (props) {
super(props);
this.state = {}
}
onChange(field, value) {
this.setState({[field]: value});
}
render () {
return <PersonFilter onChange={this.onChange.bind(this)} />
}
}
在PersonFilter
组件内部创建一个函数onFieldChange
,它将对包装器组件中的函数onChange
的引用传递给设置状态this.setState
export class PersonFilter extends React.Component {
constructor(props) {
super(props);
}
onFieldChange(event) {
const changeName = event.target.name;
const changeValue = event.target.value;
this.props.onChange(fieldName, fieldValue);
}
然后最后
<Field
onChange={this.onFieldChange.bind(this)}
className="person__input" icon="search"
name="searchName" component={renderField} type="text"
placeholder="Name"/>