这是我在React中使用Redux进行状态管理的EditStudent组件。这是我的组件代码。
import React, { Component } from 'react'
import {connect} from 'react-redux';
import {getStudentDetail} from '../actions/studentActions';
class EditStudents extends Component {
constructor(props){
super(props);
this.onInputChange = this.onInputChange.bind(this);
this.state = {
name:this.props.student.name,
email:this.props.student.email,
address:this.props.student.address
}
// this.state
}
render() {
return (
<div>
<form>
<p>
<label>Name</label>
<input type="text" name="name"
value={this.state.name}
onChange={this.onInputChange}
/>
</p>
<p>
<label>Email</label>
<input type="text" name="email"
value={this.state.email}
onChange={this.onInputChange}
/>
</p>
<p>
<label>Address</label>
<input type="text" name="address"
value={this.state.address}
onChange={this.onInputChange}
/>
</p>
<button type="submit">Update</button>
</form>
</div>
)
}
onInputChange(e){
var name = e.target.name;
this.setState({[name]:e.target.value});
}
componentDidMount(){
this.props.getStudentDetail(this.props.studentId());
}
}
let mapDispatchToProps = (dispatch,ownProps)=>{
return {
getStudentDetail: (id)=>{
dispatch(getStudentDetail(id));
},
studentId: ()=>{
return ownProps.match.params.id;
}
}
}
const mapStateToProps = (state)=> {
return {
student:state.students.student
}
}
export default connect(mapStateToProps,mapDispatchToProps)(EditStudents);
这是我在文本输入字段中显示ajax响应时遇到的问题。我在构造函数中设置组件,但是当ajax请求完成时未设置状态。
ajax完成后是否可以设置状态?
答案 0 :(得分:3)
我通过在component上添加componentWillReceiveProps()函数来解决此问题。
componentWillReceiveProps(nextProps){
this.setState({
name:nextProps.student.name,
email:nextProps.student.email,
address:nextProps.student.address
})
}
非常感谢, Sakhi Mansoor 提供帮助。
答案 1 :(得分:1)
您需要在重新呈现输入时将输入值存储在您的状态中,以免更改不会被反映出来。
进行以下更改:
constructor(props){
super(props);
this.onInputChange = this.onInputChange.bind(this);
this.state = {
email:this.props.student.email,
address: this.props.student.address
}
}
在渲染中:
<p>
<label>Email</label>
<input type="text" name="email" value={this.state.email} onChange={this.onInputChange('name)}/>
</p>
<p>
<label>Address</label>
<input type="text" name="address" value={this.state.address} onChange={this.onInputChange('name')}/>
</p>
onInputChange= name => event => {
this.setState({
[name]: event.target.value,
});
};
答案 2 :(得分:0)
有两种方法
第一-
constructor(props) {
super(props);
this.state = {
firstName: ""
};
}
componentDidMount() {
this.props.userProfile(); // Redux Action
}
componentWillReceiveProps(nextProps) {
console.log(nextProps);
this.setState({
firstName: nextProps.user.firstName
});
}
第二个-
constructor(props) {
super(props);
this.props.userProfile(); // Redux Action
this.state = {
firstName: ""
};
}
static getDerivedStateFromProps(props, state) {
return {firstName: this.props.user.firstName };
}