【发布时间】:2018-05-04 22:50:09
【问题描述】:
我正在尝试将数据从我的状态加载到我的表单中并且正在苦苦挣扎。
我登录并将电子邮件和令牌保存到 Redux 状态。当我推送到其中包含表单的测试页面时,我无法在表单中显示电子邮件。为什么我无法加载电子邮件?我可以在 TestPage.js 上看到它,但在 TestForm 上看不到。
TestPage.js
import React from "react";
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import TestForm from "../forms/TestForm";
class TestPage extends React.Component {
render() {
const { isAuthenticated, email } = this.props;
return (
<div>
{ isAuthenticated && <h1> { email } </h1> }
<TestForm submit={this.submit} props={ this.props } />
</div>
);
}
}
TestPage.propTypes = {
email: PropTypes.string.isRequired,
isAuthenticated : PropTypes.bool.isRequired
};
function mapStateToProps(state){
return {
email : state.user.email,
isAuthenticated : !!state.user.token
};
};
export default connect (mapStateToProps )(TestPage);
TestForm.js
import React from 'react'
import { Form, Button } from "semantic-ui-react";
import { connect } from "react-redux";
class TestForm extends React.Component {
state = {
name : '',
email : '',
isActive : true
}
onSubmit = e => {
e.preventDefault();
console.log("state = " + JSON.stringify(this.state));
}
componentDidMount(){
this.setState(this.props);
this.onInit(this.props);
console.log(" this props email = " + JSON.stringify(this.props));
console.log(" this state email = " + JSON.stringify(this.state.email ));
}
onInit = (props) => {
console.log(" this props email = " + JSON.stringify(this.props));
console.log(" this state email = " + JSON.stringify(this.state.email ));
}
render() {
const { state, loading } = this;
const { handleSubmit } = this.props;
return (
<div>
<Form onSubmit={this.onSubmit} loading={loading}>
<Form.Field >
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
name="email"
placeholder="example@example.com"
value={this.state.data.email}
onChange={this.onChange}
/>
</Form.Field>
<Button primary>Login</Button>
</Form>
</div>
)
}
};
function mapStateToProps(state){
return {
state : this.state
};
}
export default connect(mapStateToProps)(TestForm);
【问题讨论】:
-
看看你的mapStateToProps函数里面的表格,你做this.state,应该只有state
标签: javascript reactjs redux react-redux