无法在我的组件中使用来自 redux-form 的数据
Can't use data from redux-form inside my component
我在项目的第一页上有一个简单的 redux 表单,还有一个指向下一页的按钮,我想在其中显示表单中的数据。
import React from 'react';
import { connect } from 'react-redux';
class UsersList extends React.Component {
componentDidMount() {
console.log(this.props.form.contact.values)
// this displays the data
}
render(){
let { firstName, lastName } = this.props.form.contact.values;
// this doesn't display the data
return (
<div>
<p>{firstName}</p>
<p>{lastName}</p>
</div>
);
};
};
function mapStateToProps(state) {
return {
form: state.form
};
};
export default connect(mapStateToProps, null)(UsersList);
这是我试图显示通过表单提交的数据的组件。正如您在评论中看到的那样,当我在 componentDidMount 方法中执行“console.log(this.props.form.contact.values)”时,它工作得很好,我可以在日志中看到信息,但是当我尝试使用它实际显示 p 标签中的内容,我收到“无法读取未定义的 属性 'values'”错误。
我不知道这是否相关,但是当 console.logging 时,我在对象中获取数据。我也尝试在 return 内映射它,仍然没有成功。
感谢任何帮助!
这是正常的,因为当您更改路线时,将调用 @@redux-form/DESTROY
操作清空您的表单中的所有数据,显然是从您的 form
reducer 中清空所有数据,所以这个
function mapStateToProps(state) {
return {
form: state.form
};
};
将导致未定义。如果您需要保留表单值,您需要告诉您的表单不要在卸载时自行销毁。
reduxForm({
destroyOnUnmount: false
})(...)
我在项目的第一页上有一个简单的 redux 表单,还有一个指向下一页的按钮,我想在其中显示表单中的数据。
import React from 'react';
import { connect } from 'react-redux';
class UsersList extends React.Component {
componentDidMount() {
console.log(this.props.form.contact.values)
// this displays the data
}
render(){
let { firstName, lastName } = this.props.form.contact.values;
// this doesn't display the data
return (
<div>
<p>{firstName}</p>
<p>{lastName}</p>
</div>
);
};
};
function mapStateToProps(state) {
return {
form: state.form
};
};
export default connect(mapStateToProps, null)(UsersList);
这是我试图显示通过表单提交的数据的组件。正如您在评论中看到的那样,当我在 componentDidMount 方法中执行“console.log(this.props.form.contact.values)”时,它工作得很好,我可以在日志中看到信息,但是当我尝试使用它实际显示 p 标签中的内容,我收到“无法读取未定义的 属性 'values'”错误。
我不知道这是否相关,但是当 console.logging 时,我在对象中获取数据。我也尝试在 return 内映射它,仍然没有成功。
感谢任何帮助!
这是正常的,因为当您更改路线时,将调用 @@redux-form/DESTROY
操作清空您的表单中的所有数据,显然是从您的 form
reducer 中清空所有数据,所以这个
function mapStateToProps(state) {
return {
form: state.form
};
};
将导致未定义。如果您需要保留表单值,您需要告诉您的表单不要在卸载时自行销毁。
reduxForm({
destroyOnUnmount: false
})(...)