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

标签 javascript reactjs

我无法更新状态值。以及如何用当前状态值加载文本字段?

请看下面:

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>

……

这是回复:

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

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

状态:
Object { user: "", firstName: "", lastName: ""} ===> 状态不会改变。

最佳答案

第一个问题是你的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}  
                    />

关于javascript - 如何更改类组件中的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58109713/

相关文章:

javascript - 为什么 `onload` 事件不会在具有 Framebusting 的嵌套 iframe 上触发?

javascript - JS表单验证功能不起作用

reactjs - onScroll react 只适用于窗口?

node.js - 添加 webpack 时 react 项目依赖错误

reactjs - React Styled Components 生成过多的 css

javascript - 从 Angular Controller 调用外部库中的函数

javascript - 如何在 jQuery 中使用行和列索引创建表?

JavaScript 获取数组中最后一项的索引

javascript - Reactjs,删除 componentWillUnmount 上的事件监听器,

javascript - jQuery 等待直到函数被执行