这是工作。
var userData={
first_name : "My First Name",
last_name : "My Last Name",
email : "My Email"
};
但这不起作用
var userData={
first_name : this.state.userData.first_name,
last_name : this.state.userData.last_name,
email : this.state.userData.email
};
this.state.userData具有用户数据。它显示在日志中。这是完整的代码。
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import store, {history} from '../../store/configureStore';
import {CLIENTS} from '../../constants/entity'
import * as crudAction from '../../actions/crudAction'
// Import custom components
import AddClientForm from '../../components/client/AddClientForm.js';
import {httpBase} from '../../utils/httpBaseUtil';
class AddClientContainer extends React.Component {
constructor(props) {
super(props);
this.submitForm = this.submitForm.bind(this);
this.state = {
isFetching: true,
userData: []
};
}
componentDidMount(){
httpBase().get('clients/'+2)
.then((response) => {
this.setState({ userData: response.data.data, isFetching: false })
})
.catch((error) => {
console.log('Error: ',error);
});
this.setState({isFetching: false })
}
/**
* Submit the form.
*
* @param {object} formProps
*/
submitForm(formProps) {
this.props.actions.submitForm(CLIENTS, formProps);
}
render() {
if (this.state.isFetching){
return(<p> Loading...</p>)
}
var userData={
first_name : this.state.userData.first_name,
last_name : this.state.userData.last_name,
email : this.state.userData.email
};
return (
<AddClientForm
initialValues={userData}
onSubmit={this.submitForm}
/>
);
}
}
/**
* Map the actions to props.
*/
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators(Object.assign({}, crudAction), dispatch)
});
export default connect(null, mapDispatchToProps)(AddClientContainer)
注意:我的应用程序基于此样板。https://github.com/Bikranshu/express-react-boilerplate
在构造函数中,将其设置userData
为空数组,并在构造函数中将其设置isFetching
为true。
然后,您的组件将挂载并调用componentDidMount
,从而使API调用设置isFetching
为true。此时,您的API调用可能未完成,这意味着isFetching
为false,并且userData
为空数组。
只需删除componentDidMount
方法中的最后一行,userData
由于其类型实际上是对象,我也不会初始化为空数组。
componentDidMount(){
httpBase().get('clients/'+2)
.then((response) => {
this.setState({ userData: response.data.data, isFetching: false })
})
.catch((error) => {
console.log('Error: ',error);
});
this.setState({isFetching: false }) // Remove this line.
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句