gpt4 book ai didi

javascript - 如何在 redux-form 中使用 formValueSelector 获取更改时更新的输入字段值

转载 作者:行者123 更新时间:2023-12-03 03:10:19 27 4
gpt4 key购买 nike

我使用 redux-formformValueSelector 从字段获取输入值。我想获取更改的值,但是在 onChange 调用我的函数之后调用 @@redux-form/CHANGE 操作。所以我没有得到更新的值。我的代码:

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

最佳答案

您应该setState,而不是仅仅将 onChange 传递给操作,首先在包装器组件构造函数内初始化状态 this.state 并确保传递 props 也添加到构造函数,然后在 onChange 函数 this.setState 中设置状态并绑定(bind)它。像这样的事情:

包装组件

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"/>

关于javascript - 如何在 redux-form 中使用 formValueSelector 获取更改时更新的输入字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46976311/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com