为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕桂英546537 2021-10-29 16:07:01
我无法更新状态值。以及如何使用当前状态值加载文本字段?请参阅以下内容: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: "" } ===> 状态不会改变。
查看完整描述

3 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

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));

        ;

      } 


查看完整回答
反对 回复 2021-10-29
  • 3 回答
  • 0 关注
  • 140 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信