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

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


请参阅以下内容:


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"

......


这是回应:


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


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


STATE:

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


慕桂英546537
浏览 141回答 3
3回答

RISEBY

setState() 是异步的,您无法立即获得更新的值。您应该使用任何其他生命周期事件(componentWillUpdate() 或在 render() 中),或者您可以将回调传递给 setState(),如下所示:&nbsp; &nbsp; &nbsp; if (number !== undefined) {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({user: number}, ()=> console.log("NUMBER: ", this.state.user))&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; if (fullName !== false || firstName !== undefined) {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({firstName: firstName}, ()=>console.log("GET firstName: ",&nbsp; this.state.firstName); );&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; this.setState({lastName: lastName}, ()=> console.log("GET lastName: ",&nbsp; this.state.lastName));&nbsp; &nbsp; &nbsp; &nbsp; ;&nbsp; &nbsp; &nbsp; }&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript