【发布时间】:2023-03-28 04:03:01
【问题描述】:
我有两个组件来表示文章列表和过滤表单。每次更改任何表单字段时,我都需要发送一个包含所选过滤器的 HTTP 请求。
我有以下SearchForm 的代码:
import React from 'react';
import { reduxForm, Field } from 'redux-form';
const SearchForm = ({ onFormChange }) => (
<form>
<Field component='select' name='status' onChange={onFormChange}>
<option>All</option>
<option value='published'>Published</option>
<option value='draft'>Draft</option>
</Field>
<Field
component='input'
type='text'
placeholder='Containing'
onChange={onFormChange}
/>
</form>
);
export default reduxForm({ form: 'myCustomForm' })(SearchForm);
以下是PostsList:
import React, { Component } from 'react';
import SearchForm from './SearchForm';
import { dispatch } from 'redux';
class PostsList extends Component {
constructor(props) {
super();
this.onFormChange = this.onFormChange.bind(this);
}
onFormChange() {
// Here I need to make the HTTP Call.
console.info(this.props.myCustomForm.values);
}
componentWillMount() {
this.props.actions.fetchArticles();
}
render() {
return (
<div>
<SearchForm onFormChange={this.onFormChange} />
<ul>
{ this.props.articles.map((article) => (<li>{article.title}</li>)) }
</ul>
</div>
);
}
}
const mapStateToProps = (state) => ({
myCustomForm: state.form.myCustomForm
});
const mapDispatchToProps = (dispatch) => ({
actions: {
fetchArticles: dispatch({ type: 'FETCH_ARTICLES' })
}
});
export default connect(mapStateToProps, mapDispatchToProps)(PostsList);
虽然渲染本身没有任何问题,但当我更改表单时,myCustomForm.values 道具发生了一些非常糟糕的事情。
当我第一次这样做时,console.log(this.props.myCustomForm.values) 调用返回 undefined,下一个调用返回之前的值。
例如:
- 我加载页面并选择
draft选项。undefined已打印。 - 我选择已发布。
{ status: 'draft' }已打印。 - 我再次选择
draft...{ status: 'published' }已打印。
我检查了 redux 商店和 componend 道具。两者都根据表单交互而变化。但我的函数返回的是以前的值,而不是 onChange 发送的新值。
这显然是我的代码的问题,很可能是我将函数从父组件传递到子组件的方式。
我做错了什么?
【问题讨论】:
标签: javascript reactjs redux redux-form