Javascript 如何更改类组件中的状态?

Javascript 如何更改类组件中的状态?,javascript,reactjs,Javascript,Reactjs,我无法更新状态值。以及如何使用当前状态值加载textfield 请参阅下文: class Form extends React.Component{ constructor(props){ super(props); this.state = { user: '', firstName: '', lastName: '', email: '' } } handleChange(field, e){

我无法更新状态值。以及如何使用当前状态值加载textfield

请参阅下文:

class Form extends React.Component{
constructor(props){
    super(props);

    this.state = {
      user: '',
      firstName: '',
      lastName: '',
      email: ''
    }
  }
 handleChange(field, e){            
    let fields = this.state.fields;
    fields[field] = e.target.value;        
    this.setState({fields});
  }

  componentDidMount() {

  axios.all([
      axios.get(config.getUser),
      axios.get(config.getFullName).catch(function() { return false})
    ])
    .then(axios.spread(function (user, fullName) {

      console.log("USER: ", this.state.user)
      console.log("FULLNAME: ", this.state.fullName)
      var number = user.data.number;
      var firstName = user.data.firstName;
      var lastName = user.data.lastName;

      if (number !== undefined) {

        this.setState({user: number})
        console.log("NUMBER: ", this.state.user) ==> doesn't print

      }
      if (fullName !== false || firstName !== undefined) {

        this.setState({firstName: firstName}); 
        console.log("GET firstName: ",  this.state.firstName);  ==> doesn't print
        this.setState({lastName: lastName});
        console.log("GET lastName: ",  this.state.lastName);
      }    
  }))
 }
 render() {
  console.log("STATE: ", this.state)
    return (
        <div>
        <form name="form" onSubmit= {this.formSubmit.bind(this)} style={{minWidth: '515px'}}> 
            <Header title="Request" />
            <Paper style={styles.paperRequestForm}>
                <Grid container>
                    <TextField
                        required
                        name="number"
                        type="text"
                        label="number"
                        margin="dense"
                        variant="outlined"
                        // InputProps={{
                        //readOnly: true,
                        // }}
                        style={{width:202.5}}
                        InputProps={{
                          autoComplete: 'off',
                          style: {
                            font: '14px arial,serif',
                            backgroundColor: "white"
                            }}}
                        InputLabelProps={{
                          style: {
                              font: '14px arial,serif',
                              backgroundColor: "white"
                              }}}
                        onChange={this.handleChange.bind(this, "number")}
                        value={this.state.user} ==> does not load data 
                    />
                </Grid>
类表单扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
用户:“”,
名字:'',
姓氏:“”,
电子邮件:“”
}
}
handleChange(字段,e){
让fields=this.state.fields;
字段[字段]=e.target.value;
this.setState({fields});
}
componentDidMount(){
axios.all([
获取(config.getUser),
get(config.getFullName).catch(函数(){return false})
])
.then(axios.spread)(函数(用户,全名){
log(“用户:”,this.state.USER)
log(“FULLNAME:,this.state.FULLNAME”)
变量编号=user.data.number;
var firstName=user.data.firstName;
var lastName=user.data.lastName;
如果(数字!==未定义){
this.setState({user:number})
console.log(“NUMBER:,this.state.user)==>不打印
}
if(全名!==false | |名字!==未定义){
this.setState({firstName:firstName});
console.log(“GET firstName:,this.state.firstName”);=>不打印
this.setState({lastName:lastName});
log(“GET lastName:,this.state.lastName”);
}    
}))
}
render(){
log(“STATE:,this.STATE”)
返回(
不加载数据
/>

以下是回应:

用户:对象{编号:“541”}

全名: 对象{“firstName”:“Dee”,“lastName”:“Williamson”}

状态:
对象{user:,firstName:,lastName::}==>状态不会更改。

setState()是异步的,无法在立即行中获取更新的值。您应该使用任何其他生命周期事件(componentWillUpdate()或render()中),或者可以按如下方式向setState()传递回调:

      if (number !== undefined) {

        this.setState({user: number}, ()=> console.log("NUMBER: ", this.state.user))
      }
      if (fullName !== false || firstName !== undefined) {

        this.setState({firstName: firstName}, ()=>console.log("GET firstName: ",  this.state.firstName); ); 
        this.setState({lastName: lastName}, ()=> console.log("GET lastName: ",  this.state.lastName));
        ;
      } 

您好,请更改您的
handleChange
函数和文本字段,希望对您有所帮助。 谢谢

handleChange=(e)=>{
这是我的国家({
[e.target.name]:e.target.value
});
}
这个.handleChange(e)}
值={this.state.user}
/>

第一个问题是你的handleChange功能,它所做的与你实习它所做的完全不同

应该是这样

handleChange = (e) => {            
    this.setState({
        [e.target.name]:e.target.value
    });
}
其次,您的componentDidMount()似乎也在访问不存在的字段。如果我们考虑您提供的响应,它应该如下所示


  componentDidMount() {

  axios.all([
      axios.get(config.getUser),
      axios.get(config.getFullName).catch(function() { return false})
    ])
    .then(axios.spread(function (user, fullName) {
      //here you should instead log the response(user and fullName) and not the states
      console.log("USER: ", user)
      console.log("FULLNAME: ", fullName)
      //basing on the format you provided on your post this is how you shoud extract them
      var number = user.number;
      var firstName = fullName.firstName;
      var lastName = fullName.lastName;

      if (number !== undefined) {

        this.setState({user: number}, console.log("NUMBER: ", this.state.user))


      }
      if (fullName !== false || firstName !== undefined) {
        //the printing is done in a callback to setState
        this.setState({firstName: firstName}, console.log("GET firstName: ",  this.state.firstName)); 
        ; 
        this.setState({lastName: lastName});

      }    
  }))
 }
最后,您的文本字段应该如下所示

                    <TextField
                        required
                        //note here the name is user and not number
                        name="user"
                        type="text"
                        label="number"
                        margin="dense"
                        variant="outlined"
                        // InputProps={{
                        //readOnly: true,
                        // }}
                        style={{width:202.5}}
                        InputProps={{
                          autoComplete: 'off',
                          style: {
                            font: '14px arial,serif',
                            backgroundColor: "white"
                            }}}
                        InputLabelProps={{
                          style: {
                              font: '14px arial,serif',
                              backgroundColor: "white"
                              }}}
                        //call the handleChange here
                        onChange={this.handleChange}
                        value={this.state.user}  
                    />


根据您的响应对象,不应该
var number=user.number
而不是
var number=user.data.number
?因此,它永远不会进入if语句内部。首先,您的handlechange方法是从不存在的状态访问字段
                    <TextField
                        required
                        //note here the name is user and not number
                        name="user"
                        type="text"
                        label="number"
                        margin="dense"
                        variant="outlined"
                        // InputProps={{
                        //readOnly: true,
                        // }}
                        style={{width:202.5}}
                        InputProps={{
                          autoComplete: 'off',
                          style: {
                            font: '14px arial,serif',
                            backgroundColor: "white"
                            }}}
                        InputLabelProps={{
                          style: {
                              font: '14px arial,serif',
                              backgroundColor: "white"
                              }}}
                        //call the handleChange here
                        onChange={this.handleChange}
                        value={this.state.user}  
                    />